代码之家  ›  专栏  ›  技术社区  ›  Johan Rin

在main.ts中使用构造函数注入服务

  •  0
  • Johan Rin  · 技术社区  · 7 年前

    在我的Angular项目中,我使用AWS Amplify来处理身份验证。

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

    所以我安装了 ngx-cookie

    梅因酒店

    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,在参数中添加构造函数似乎是不可能的 梅因酒店 .

    问题: :如何在中通过服务 梅因酒店 ?

    谢谢你的帮助。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Community Mohan Dere    6 年前

    那么 main.ts 是角度应用程序的入口点。在这里,我们无法查询服务实例或将其注入,因为我们在Angular应用程序之外。看起来是这样的 Storage

    example 这个存储类的所有属性都是静态的,所以我不确定配置是否需要一个类的实例。

    我的一个想法是劫机 APP_INITIALIZER 什么时候 需要对其进行配置,因此这可能有效,也可能无效:

    App.module.ts

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

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

    因此,在我们的 deps 条目被实例化并按顺序注入工厂,我们可以创建一个 MyStorage cookieService 从喷油器中拔出。

    同样,如果MyStorage上的属性必须是静态的,那么这里需要一个不同的解决方案。在我看来好像 MyStorage 角度应用程序不应知道,但取决于是否需要在