How to pass dependencies to @auth0-angular-jwt?

寵の児 提交于 2019-12-08 00:23:16

问题


So... I'm migrating my "old" code that was using the HttpModule and angular2-jwt lib.

Before, I could make angular2-jwt work with the following config:

export function authHttpServiceFactory(
  http: Http, options: RequestOptions, myService: MyService) {

  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Content-Type': 'application/json'}],
    noJwtError: true,
    tokenGetter: (() => myService.get('my_token'))
  }), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions, MyService]
    }
  ]
})
export class AuthModule {}

... But now, to use it with the new HttpClientModule I have to use the new version of angular2-jwt (@auth-angular-jwt - I know it's still in beta version) and I'm trying to figure out that I need to do to access my service to get the token (as I used to do).

My actual config is (same as git's example):

@NgModule({
  // ...
  imports: [
    HttpClientModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: () => {
          return <myService>.getToken(); // Here
        }
      }
    })
  ]
})
export class AppModule {}

Is it possible? Thanks in advance.


回答1:


This can be done by overriding config service:

export const jwtOptionsFactory = (dependency) => ({
    tokenGetter: () => dependency.getToken(),
    whitelistedDomains: []
});

...
imports: [
    JwtModule.forRoot({
        config: { tokenGetter(): string { throw new Error('no tokenGetter') } }
    })
],
providers: [{
    provide: JWT_OPTIONS,
    deps: [Dependency],
    useFactory: jwtOptionsFactory
}]

Starting from 1.0.0-beta.8, forRoot accepts options provider:

...
imports: [
    JwtModule.forRoot({
        jwtOptionsProvider: {
            provide: JWT_OPTIONS,
            deps: [Dependency],
            useFactory: jwtOptionsFactory
        }
    })
]


来源:https://stackoverflow.com/questions/45405914/how-to-pass-dependencies-to-auth0-angular-jwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!