如何使angular2模块(ngModule)可配置

时间:2017-02-02 08:23:42

标签: angular typescript angular-module ng-modules

假设我们有一个模块可以在其中执行一些身份验证。

我想在将模块添加到项目时设置一些变量。

我已经看到路由模块使用函数forRoot(routes)执行类似操作。

所以我尝试了同样但感觉不正确。

我的身份验证模块(应该是可配置的)

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: []
})
export class AuthenticationModule {
  static forRoot(authMode: AuthMode) {
    return {
      ngModule: AuthenticationModule,
      providers: [
        {
          useValue: authMode,
          provide: AuthMode
        },
        {
          provide: AuthenticationGuard,
          useFactory: authFactory,
          deps: [AuthMode, Router]
        }
      ]
    }
  }
}

export function authFactory(authMode: AuthMode, router: Router) {
  return new AuthenticationGuard(authMode, router);
}

AuthMode只是一个enum保存值,以便稍后在AuthenticationGuard中比较所选模式。

我的app.module.ts添加了这样的模块:

@NgModule({
  declarations: [ // some stuff ]
  imports: [
    BrowserModule,
    // ... some other stuff
    AuthenticationModule.forRoot(AuthMode.OAuthLocalStorage)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

AuthenticationGuard按这样的值注入authMode

@Injectable()
export class AuthenticationGuard implements CanActivate {
  public storage: Storage;

  constructor(@Inject(AuthMode) authMode, private router: Router) {
    console.log('selected authMode is ', AuthMode[authMode]);
}

使用具有路由和canActivate属性的后卫时,此方法正常。但是一旦我将它注入其他服务(在另一个模块中),我就会收到此错误:

错误:NgModule' AuthenticationModule'无效的提供商 - 只允许Provider和Type的实例,得到:[?undefined?,...]在SyntaxError.ZoneAwareError

所以我的基本问题是:

  • 这是如何制作ngModule 可配置
  • 的方法
  • 什么可以解决上面的问题?

使用Angular 2和angular-cli(beta 25)构建

1 个答案:

答案 0 :(得分:0)

如何将设置存储在特殊变量中并使用工厂注入它?

ToolbarItem
相关问题