user1636505 user1636505 - 9 days ago 7
TypeScript Question

Using instantiated dependency in NgModule

I have the root

AppModule
in which I describe dependencies and I have
@Injectable
JwtLocalStorage
. I wonder how can I pass
JwtLocalStorage.prototype.getToken()
as
tokenGetter
in
provideAuth()
. Is it possible? What I should to do for that?

app.module.ts

@NgModule({
// ...
providers: [
// ...
provideAuth({
tokenGetter: () => JSON.parse(localStorage.getItem(TASK_DI_CONFIG.jwtName)),
}),
{ provide: APP_CONFIG, useValue: TASK_DI_CONFIG },
{ provide: JwtStorage, useClass: JwtLocalStorage }
],
bootstrap: [
AppComponent
]
})
export class AppModule {

}


jwt-local-storage.ts

@Injectable()
export class JwtLocalStorage implements JwtStorage {
constructor(
@Inject(APP_CONFIG) private config: AppConfig
) {

}

getToken() {
return JSON.parse(localStorage.getItem(this.config.jwtName));
}
// ...
}


P.S. I'm using Angular
2.0.0-rc.5

Answer

I solved this issue by using service factory. Solution looks like this

@NgModule({
    // ...
    providers: [
        // ...
        {
            provide: AuthHttp,
            useFactory: (http: Http, jwtStorage: JwtStorage) => {
                return new AuthHttp(new AuthConfig({
                    tokenGetter() {
                        return jwtStorage.getToken();
                    }
                }), http);
            },
            deps: [Http, JwtStorage]
        }
    ]
})
export class MyAwesomeModule {

}