在我的应用程序中,我使用我们自己的实现扩展了 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 服务/类中调用它,因为参数已经传递......