2
import { NgModule} from '@angular/core';
export const my_custom_format{
var date_format=localStorage.getItem('date_format')
}
...

@NgModule({
  imports [
  ...
  ],
  declarations [
  ...
  ],
  entryComponents [
  ...
  ],
  providers [
  {provide: LOCALE_ID, useValue:date_format}
  ]
})

And when I come to page, my date_format gets the value from localStorage. But if my item in locaLstorage gets change, date_format is not updating. How to do that?

1
  • {provide: OWL_DATE_TIME_FORMATS, useValue:date_format} Commented Sep 25, 2019 at 10:35

3 Answers 3

1

Imporant - This is a hack and I don't know if it will achieve what you are trying to do. My guess is that you are trying to inject the locale id to some of your components and use them there.

If you are trying to change the language this way, then I'm sorry to tell you that it does not work by changing the locale id from your local storage.

You can try the following (and see if it works)

export class LocalStorage {
    public static get DateFormat() {
        return localStorage.getItem('date_format');
    }
}

and for the providers part:

{provide: OWL_DATE_TIME_FORMATS, useValue:LocaleStorage.DateFormat}
Sign up to request clarification or add additional context in comments.

2 Comments

Dear sir, but whenever I change value in localStorage the application gets old one value from localStorage not updated one this is main problem
I really don't understand the problem. Can you explain it more thoroughly please? How do you know that the application does not get the new value. What is the syptom?
1

The way dependency injection (DI) works in angular, the only way, at least for now, is to save the value in localStorage & refresh the app/page & then pick that value in either useFactory,useValue or useClass on app load.

In a component's life cycle, there is just one runtime execution that happens for the providers. If we want to change the provider, we have to unmount & remount the component again, as far as I know.

2 Comments

Could you please explain how to unmount and remount a component?
Check this SO answer, hope it helps. stackoverflow.com/a/52354498/4109794 If it doesn't, try refresh the angular app & pick value from localStorage etc using useValue
0

In angular, providers are a singleton classes, meaning that they are initialized once and each place (component etc) that will request for it will get the same instance that was initialized.

After we understands this we can understand your case. The value of LOCAL_ID get initialized once with date_format value, from here on the value of LOCAL_ID won't get updated with changes to date_format.

One thing you can do, is to have this provider in each component that you want that will get the latest value of date_format.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.