【问题标题】:Can you use the Angular app.component to write application settings to local storage?您可以使用 Angular app.component 将应用程序设置写入本地存储吗?
【发布时间】:2019-06-12 20:26:46
【问题描述】:

我可以使用应用组件将设置写入本地存储,然后从其他组件访问设置吗?

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));
});

【问题讨论】:

  • 这有关系吗?无论如何你都在调用异步方法。
  • @ABOS 我不确定。我是 Angular 的新手。我想可能只是因为组件内的代码是异步的,并不意味着一个组件会等待另一个组件。
  • Angular APP_INITIALIZER 可能是你想要的。大量在线教程,请查看。

标签: angular


【解决方案1】:

解决您的问题的正确方法是为工厂提供APP_INITIALIZER 令牌。

例子:

@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.
        });
}

更多信息,您可以查看herehere

【讨论】:

  • 谢谢。这正是我一直试图找到的答案。三门关于 Angular 的 Udemy 课程,但没有一门解释了这一点。
  • 我成功地实现了你的答案。谢谢。
【解决方案2】:

为了在使用任何组件之前进行设置,无论您的应用程序的入口点如何,您都可以考虑使用APP_INITIALIZER

APP_INITIALIZER:在应用初始化之前调用回调。全部 注册的初始化器可以选择返回一个 Promise。全部 返回 Promises 的初始化函数必须在 应用程序被引导。如果其中一个初始化程序失败 解决,应用程序未引导。

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

【讨论】:

  • 我同意。但是,我选择了@tiagodws 答案,因为他使用了一个示例。我喜欢例子:)
  • @GregHarner 您选择了更好的答案,这一点毫无疑问。我只是想知道投反对票的原因。一切都好;)
猜你喜欢
  • 1970-01-01
  • 2019-10-16
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多