我想扩展Http
提供程序以拦截所有发送403状态以处理自动注销的请求。 我的自定义InterceptingHttp
应该声明为Http
提供程序,所以我不需要关心“特殊”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这是正确的。这是剩下的。谢谢 –