如何从订阅中"嗅探"数据并仍然返回可观察量<Response>



我有这个角度http的子类,它在我的应用程序中需要的任何地方都被优雅地注入。问题是:我需要检查一些值,即使它们不是 http 错误代码,并返回可观察响应。问题是订阅返回订阅。

此类的目的是透明地处理一些常见的全局 http 错误(而 http errors -> catch block;或 api errors -> json 字段以在订阅块中检查)。

import {Injectable} from '@angular/core';
import {Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Request, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class CustomHttpService extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }
    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return super.request(url, options)
            .catch((error: any) => {
                // Do something here, maybe some redirect.
                return Observable.throw(error);
            })
            .subscribe(res => {
                if (res.json().status === 401) {
                    // Do something here, maybe some redirect too.
                }
                return Observable.of(res);
            });
    }
}

我正在阅读 rxjs 文档,但我仍然对许多概念感到困惑。任何帮助将不胜感激。

使用 map() 而不是 subscribe,订阅是管道的末端,处理程序,你想修改它。

.map(res => {
  if (res.json().status === 401) {
    // Do something here, maybe some redirect too.
  }
  return res;
});

最新更新