简体   繁体   中英

Injecting providers in angular2

Following the tutorial here:

https://auth0.com/blog/2016/02/18/ionic-2-authentication-how-to-secure-your-mobile-app-with-jwt/

The way AuthHttp is injected as a provider is :

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [
    provide(AuthHttp, {
      useFactory: (http) => {
        return new AuthHttp(new AuthConfig, http);
      },
      deps: [Http]
    })
  ]
})

This seems quiet complex. As I understand providers accepts an array of providers.

Is there a easier way to rewrite this code ?

If AuthHttp has an @Injectable() decorator then this should work as well

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [HTTP_PROVIDERS, AuthConfig, AuthHttp]
})

I think that you need to have the AuthConfig provided by the providers. If it's just using the constructor without parameters, the Günter's answer is what you're looking for!

If you need to specify parameters when instantiating this class, you could try the following:

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [
    HTTP_PROVIDERS,
    provide(AuthConfig, { useValue: new AuthConfig(param1, ...) }),
    AuthHttp
  ]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM