Angular 2 将服务注入(inject)服务

标签 angular dependency-injection angular2-services angular2-di

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

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 还需要注入(inject) Secure_Http 类/服务,因为那里需要一个函数来获取 JWT。

但是,一旦我将 Secure_Http 类/服务添加为构造函数参数,我就会收到错误没有 Secure_Http 提供程序

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

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

最佳答案

如果您明确想要注入(inject)Secure_Http,则需要提供

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

这种方式都会导致 Secure_Http 被注入(inject)

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

但是如果您知道 Http 注入(inject) Secure_http (正如您的配置所做的那样),您可以直接强制转换

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

关于Angular 2 将服务注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122234/

相关文章:

node.js - 是什么原因导致 localhost :4200 to be added in front of route call?

c# - DryIoc、LightInject 体验

c# - 无法解决依赖项时抛出异常

javascript - localStorage 似乎在 Angular 中不起作用

angular - 在 Angular 2 延迟加载模块中使用外部 javascript 库,而不是 index.html

typescript - Angular 2 : manipulate element outside directive

angular - 在 Angular2 的路由器中获取事件路由上的组件实例?

java - @Bean 和 @Autowired 的区别

json - HTTP 请求 Angular 2

angular - 如何使用 ngx-bootstrap 创建通用通知,如 toastr 通知