【发布时间】:2016-09-12 00:29:51
【问题描述】:
我正在使用 RC6,并试图弄清楚如何在整个应用程序中捕获 HTTP 错误 - 特别是身份验证错误。
有许多帖子描述了如何使用自定义类扩展 Http 类,但我不确定如何注册新类,因为它看起来语法随着最近的 ngModule 更改而改变.
这是类(添加了所有相关的导入):
@Injectable()
export class InterceptedHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super( backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return super.get(url,options);
}
}
我认为我可以在@ngModule 的providers 部分执行以下操作:
imports: [ HttpModule, ... ],
providers: [
...
InterceptedHttp,
{provide: Http, useClass: InterceptedHttp },
ConnectionBackend
],
但这只会给我带来一堆缺失的模块错误:
ERROR in [default] C:/WebConnectionProjects/AlbumViewer/Web/src/app/app.module.ts:64:10
Argument of type '{ imports: (ModuleWithProviders | typeof BrowserModule)[]; declarations: (typeof AlbumList | type...' is not assignable to parameter of type 'NgModuleMetadataType'.
Types of property 'providers' are incompatible.
Type '(typeof ConnectionBackend | typeof Album | typeof Artist | typeof Track | typeof AppConfiguration...' is not assignable to type 'Provider[]'.
Type 'typeof ConnectionBackend | typeof Album | typeof Artist | typeof Track | typeof AppConfiguration ...' is not assignable to type 'Provider'.
Type 'typeof ConnectionBackend' is not assignable to type 'Provider'.
Type 'typeof ConnectionBackend' is not assignable to type 'FactoryProvider'.
Property 'provide' is missing in type 'typeof ConnectionBackend'.
删除添加的行,一切正常。
那么,如何注册一个自定义的 Http 类呢?
【问题讨论】:
-
昨天刚刚问了几乎相同的问题。我的回答有点接近@BeetleJuice 下面的建议。更健壮一点。 stackoverflow.com/questions/39422218/…