角度2:扩展响应类

时间:2016-03-21 20:09:19

标签: angular

我是Angular 2的新手,我想要扩展Response类。 基本上我试图做的是,对于每个响应(在返回调用请求的对象之前),我想检查响应状态并对其执行某些操作。例如,如果响应状态为401,则导航到登录屏幕。

这是我到目前为止所做的:

export class MyResponse extends Response {
  constructor(responseOptions: ResponseOptions) {
    super(responseOptions);
  }

和我的靴子:

provide(Response, {useClass: MyResponse}),

当我正在运行时:

  

未捕获的TypeError:无法读取属性' getOptional' of undefined_runAppInitializers @ application_ref.js:224PlatformRef _._ initApp @ application_ref.js:205PlatformRef_.application @ application_ref.js:153bootstrap @ browser.js:101(匿名函数)@ app.js:59DecorateConstructor @Reflect.js:536decorate @Reflect.js :98__decorate @ app.bundle.js:3181(匿名函数)@ app.ts:13(匿名函数)@ app.ts:56__webpack_require__ @ bootstrap e77d89d ...:19(匿名函数)@ bootstrap e77d89d ...:39__webpack_require__ @ bootstrap e77d89d ... :19(匿名函数)@ bootstrap e77d89d ...:39(匿名函数)@ bootstrap e77d89d ...:39(匿名函数)@travesseyJwtHttp.ts:46__webpack_require__ @ bootstrap e77d89d ...:19(匿名函数)@ app.ts:7__webpack_require__ @ bootstrap e77d89d ...:19(匿名函数)@ bootstrap e77d89d ...:39__webpack_require__ @ bootstrap e77d89d ...:19(匿名函数)@ bootstrap e77d89d ...:39(匿名函数)@ bootstrap e77d89d ...:39    `

有没有更好的方法来做我想做的事情?

2 个答案:

答案 0 :(得分:2)

事实上,在查看了XHRConnection类的实现(参见https://github.com/angular/angular/blob/master/modules/angular2/src/http/backends/xhr_backend.ts#L59)后,Response无法通过依赖注入进行更改,因为它直接实例化了收到回复。

如果你想拦截回复,我认为方法是扩展Http对象本身并利用catch运算符:

@Injectable()
export class CustomHttp 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).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

可以按如下所述注册CustomHttp类:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

如果此级别出现401错误,您可以在为catch运营商提供的回调中“捕获”它们。

答案 1 :(得分:1)

看起来只缺少@Injectable()注释

@Injectable()
export class MyResponse extends Response {
  constructor(responseOptions: ResponseOptions) {
    super(responseOptions);
  }
}