【发布时间】:2016-12-19 15:11:05
【问题描述】:
我想扩展 Http 提供程序以拦截所有提供 403 状态的请求以处理自动注销。
我的自定义 InterceptingHttp 应该声明为 Http 提供程序,所以我不需要关心“特殊”http 提供程序。
我必须关注:
我的自定义 Http 提供程序
import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthenticationService } from './../services/authentication.service';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class InterceptingHttpService extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions, private authenticationService: AuthenticationService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
var self = this;
return super.request(url, options).catch((res: Response) => {
if (res.status === 403) {
console.log('intercepted');
self.authenticationService.logout();
}
return Observable.throw(res);
});
}
}
在 NgModule 中作为常规 Http 提供者的声明
@NgModule({
imports: [
BrowserModule,
ToastyModule.forRoot(),
HttpModule,
FormsModule,
routing,
Ng2BootstrapModule,
PaginationModule
],
declarations: [
AppComponent,
NavHeaderComponent,
FooterCopyrightComponent,
InventoryRootComponent,
InventoryTreeComponent,
InventoryDetailComponent,
SetModelComponent,
MetadataListComponent,
MetadataDetailComponent,
ScriptGeneratorComponent,
SetDetailComponent,
SetVersionComponent,
SetContainerTreeComponent,
SetContainerDetailComponent,
FilterByPropertyPipe,
OrderContainersByLeafPipe,
ResolveStateId,
ConfirmComponent,
FocusDirective
],
providers: [
SetService,
SetTypeService,
SetContainerService,
StateService,
NotificationService,
MetadataService,
MetadataTypeService,
EntityService,
SetContainerMetadataService,
AuthenticationService,
InterceptingHttpService,
ConfirmService,
SiteVersionService,
{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, authenticationService: AuthenticationService) => {
return new InterceptingHttpService(backend, defaultOptions, authenticationService);
},
deps: [XHRBackend, RequestOptions, AuthenticationService]
},
],
bootstrap: [AppComponent]
})
它被加载并拦截所有 403 响应。唯一奇怪的是,authenticationService 是未定义的。
我想我的供应商声明可能有误。我尝试将AuthenticationService 添加到deps 数组中,这只会导致循环依赖错误。
我的错误在哪里?如何在我的扩展 Http 提供程序中使用我的AuthenticationService?
【问题讨论】:
-
如果你使用
() =>,则不需要self。 -
你在
constructor(...) { super(...); console.log(authenticationService); }这样的构造函数中检查过是否传入了值吗? -
@GünterZöchbauer 没错。这是一个遗留物。谢谢
-
果然是
undefined -
您使用的是哪个 Angular2 版本?不久前 DI 和扩展类存在问题。
标签: angular dependency-injection angular2-http