【问题标题】:Inject a service with constructor in the main.ts在 main.ts 中使用构造函数注入服务
【发布时间】:2018-12-10 21:59:17
【问题描述】:

在我的 Angular 项目中,我使用 AWS Amplify 来处理我的身份验证。 现在,我想将其配置为使用 cookie 管理令牌。

阅读文档后发现需要在main.ts中提供my own storage to Amplify。

所以我安装了ngx-cookie 并开始在库方法和 AWS Amplify 签名之间进行映射,如下所示:

ma​​in.ts

class MyStorage {

  constructor(private cookieService: CookieService) { }

  setItem(key: string, value: string) {
    this.cookieService.put(key, value);
  }

  getItem(key: string): string {
    return this.cookieService.get(key);
  }

}

Amplify.configure({
  ...amplify,
  Auth: {
    oauth: oauth,
    cookieStorage: {
      domain: 'localhost'
    },
    storage: new MyStorage(), <--- expect a cookieService here
  }
});

问题:new MyStorage() 期望参数中有一个 cookieService,并且似乎无法在 main.ts 中添加构造函数。

问题:如何在main.ts传递服务?

感谢您的帮助。

【问题讨论】:

    标签: angular amazon-cognito aws-amplify


    【解决方案1】:

    嗯,main.ts 是 Angular 应用程序的入口点。在这里,我们无法查询服务实例或将它们注入,因为我们在 Angular 应用程序之外。看起来Storage 对象也与 Angular 应用程序完全解耦,因此您必须自己进行任何依赖注入。

    另外值得注意的是:虽然我找不到任何明确的文档,但亚马逊的 example 这个 Storage 类的所有属性都是静态的,所以我不确定配置是否需要一个上课。

    我的一个想法是劫持APP_INITIALIZER,以便在应用程序首次引导时获取 DI 令牌。但是,我对 Amplify 不熟悉,所以我不知道什么时候需要配置它,所以这可能会也可能不会:

    App.module.ts

    providers: [
      {
        provide: APP_INITIALIZER,
        useFactory: amplifyConfigFactory,
        deps: [CookieService],
        multi: true
      }
    ]
    

    amplifyConfigFactory.factory.ts

    export function amplifyConfigFactory(cookieService: CookieService) {
      Amplify.configure({
        // ....
        storage: new MyStorage(cookieService)
      });
    
      return () => Promise.resolve(); // factories must return a Promise
    }
    

    所以,上面我们的deps 条目被实例化并按顺序注入到工厂中,我们可以使用注入器中的cookieService 创建一个MyStorage。

    同样,如果 MyStorage 上的属性必须是静态的,那么您将需要一个不同的解决方案。在我看来 MyStorage 不应该是 Angular 应用程序已知的东西,但取决于是否需要在 APP_INITIALIZER 钩子之前配置 Amblify,这可能会起作用。

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多