繁体   English   中英

Angular 2将服务注入服务

[英]Angular 2 inject service into service

在我的应用程序中,我使用自己的实现扩展了Angular Http类,该实现添加了一些标头。

export class Secure_Http extends Http {
    private getJwtUrl = environment.employerApiUrl + '/getJwt';
    private refreshJwtUrl = environment.employerApiUrl + '/refreshJwt';

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private storage: SessionStorageService) {
        super(backend, defaultOptions);
    }

然后,在app.mobule.ts文件中,我这样做了,因此每次都使用我们的安全版本而不是基本版本:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ....
  ],
  providers: [
    ....
    SessionStorageService,
    {
      provide: Http,
      useFactory: secureHttpFactory,
      deps: [XHRBackend, RequestOptions, SessionStorageService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function secureHttpFactory(backend: XHRBackend, options: RequestOptions, sessionStorage: SessionStorageService) {
    return new Secure_Http(backend, options, sessionStorage);
}

现在,在我们的服务中,我们使用标准的构造函数/ DI方法:

@Injectable()

export class MySecurityService {
    employerApiBaseUrl: string = environment.employerApiUrl;

    constructor(private _http: Http) { } //, private _secureHttp: Secure_Http

    getUser() : Observable<User> {
        this.log('getUser', 'getting the current user');

        var thisUrl = this.employerApiBaseUrl + '/jwt/userinfo';

        var searchParam = {
            jwt: this.getToken()
        };

        return this._http.post(thisUrl, searchParam)
            .map((response: Response) => this.extractGetUserResponse(response))
            .catch(this.handleError);
    }
}

现在我的问题是,SecurityService还需要注入Secure_Http类/服务,因为那里需要获取JWT的一个功能。

但是,一旦我将Secure_Http类/服务添加为构造函数参数,就会收到错误No provider for Secure_Http

因此,我的下一个想法是将Secure_Http添加到app.module.ts文件中的providers部分,就在我指定Http需要使用Secure_Http的位置旁边。 但是,一旦这样做,我就会收到错误No provider for ConnectionBackend 如果我转过身并将ConnectionBackend添加到提供程序中,则@NgModule上会出现错误,表明无法将Type 'typeof ConnectionBackend' is not assignable to type provider

我在哪里错了? 我只有一种方法需要直接在Secure_Http类上访问。 这是必需的,因为它必须是我的一个帖子调用的参数。 我不能仅仅从Secure_Http服务/类中调用它,因为参数已经传递了。

如果您明确想要注入Secure_Http ,则需要提供它

{
  provide: Secure_Http,
  useFactory: secureHttpFactory,
  deps: [XHRBackend, RequestOptions, SessionStorageService]
},
{ provide: Http, useExisting: Secure_Http }

这样都导致Secure_Http被注入

constructor(private _http: Http) { } 
constructor(private _secureHttp: Secure_Http) {}

但是如果您知道Http注入Secure_http (如您的配置那样),则可以进行Secure_http

private _http: SecureHttp;
constructor(http: Http) { 
  this._http = http as Secure_Http;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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