0

Can I use the app component to write settings to local storage and then access the settings from other components?

await docRef.get().then(doc => {
   localStorage.setItem("appAdmin", JSON.stringify(doc.data().appAdministrator));
   localStorage.setItem("authorizeDomain", JSON.stringify(doc.data().authorizedDomain));
   localStorage.setItem("contactAdmin", JSON.stringify(doc.data().contactAdministrator));
   localStorage.setItem("contactGroup", JSON.stringify(doc.data().appContactGroup));
});
Greg Harner
  • 145
  • 1
  • 13
  • 2
    does it matter? you are calling async method anyway. – ABOS Jan 18 '19 at 14:51
  • @ABOS I'm not sure. I'm new to Angular. I thought maybe just because the code inside a component was async that did not mean that one component will wait for another. – Greg Harner Jan 18 '19 at 14:55
  • 1
    Angular APP_INITIALIZER is probably what you want. tons of tutorials online, check it out. – ABOS Jan 18 '19 at 14:58

2 Answers2

2

The correct approach to your problem would be to provide a factory with the APP_INITIALIZER token.

Example:

@NgModule({
    providers: [
        {
            provide: APP_INITIALIZER,
            useFactory: appInitializerFactory,
            deps: [/* Your dependencies */],
            multi: true,
        },
    ],
})
export class AppModule {}

export function appInitializerFactory(/* The injection of your dependencies, in the same order as above */) {
    return () =>
        new Promise<any>((resolve: any) => {
            // Do your async work, call `resolve()` when done.
        });
}

For more information, you can check here or here.

tiagodws
  • 1,345
  • 13
  • 20
1

for setting up things before any component is used and regardless of the entry point of your app, you might consider using APP_INITIALIZER.

APP_INITIALIZER: Callback is invoked before an app is initialized. All registered initializers can optionally return a Promise. All initializer functions that return Promises must be resolved before the application is bootstrapped. If one of the initializers fails to resolves, the application is not bootstrapped.

ref: https://angular.io/guide/dependency-injection-providers#predefined-tokens-and-multiple-providers

dee zg
  • 13,793
  • 10
  • 42
  • 82
  • I agree. However, I picked @tiagodws answer because he used an example. I like examples :) – Greg Harner Jan 18 '19 at 15:18
  • @GregHarner you've picked better answer, no doubt about that. i was just wondering about reasons for downvote. all good ;) – dee zg Jan 18 '19 at 15:19