Angular4 - 所有 http 请求的中央错误记录和处理

Angular4 - Central error Logging and handling for all http requests

我为我的所有 http 调用开发了以下包装器 class。我刚刚在示例中包含了 get 函数

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

/**
 * Wrapper around the Http provider to allow customizing HTTP requests
 */
@Injectable()
export class HttpClientService {
    private httpParams: HttpParams;
    private httpHeaders: HttpHeaders;

    constructor(
        private httpClient: HttpClient,
        private sharedService: SharedService) {
        this.httpParams = new HttpParams();
        this.httpHeaders = new HttpHeaders({ 'Access-Control-Allow-Origin': '*' });

    }

    public get<T>(url: string, httpParams: Array<Map<string, string>>) {
        return this.httpClient
            .get<T>(url, { params: this.appendHttpParams(httpParams), headers: this.httpHeaders })
            .subscribe(data => {
                console.log(data);
            },
            err => {
                console.log(err);
            });

    }

    private appendHttpParams(paramArray: Array<Map<string, string>>): HttpParams {
        paramArray.forEach((value: Map<string, string>, index: number, array: Array<Map<string, string>>) => {
            this.httpParams.append(value.keys[index], value.values[index]);
        });
        return this.httpParams;

    }
}

这很好用。但是当我尝试按如下方式从自定义服务调用 get 时

this.httpClientService.get<StoredAppData[]>(this.configService.urls.fetchSettings, params)
    .map((response) => {
        this.storedAppData = response.json();
        console.log(this.storedAppData);
        return this.storedAppData;
    });

它抛出一个 TS2339: 属性 'map' does not exist on type 'Subscription' 错误。我知道我已经订阅了 Observable 并且如果我摆脱 .subscribe() 并且只是 return 函数会很好地工作。但是,我无法在单层上实施中央错误处理。有什么好的方法可以做到这一点?

我可以通过将 .subscribe() 替换为 .do() 运算符来实现。

类型错误解决了代码中的实际问题。订阅不应 return 从应该 return 可观察的方法编辑:

const response$ = this.httpClient.get<T>(...)
response$.subscribe(data => ..., err => ...);
return response$;

除非 return 热观察是一个理想的效果,subscribe 根本不应该在服务本身中执行。相反,do operator 应该用于副作用:

This operator is useful for debugging your Observables for the correct values or performing other side effects.

Note: this is different to a subscribe on the Observable. If the Observable returned by do is not subscribed, the side effects specified by the Observer will never happen. do therefore simply spies on existing execution, it does not trigger an execution to happen like subscribe does.

return this.httpClient.get<T>(...)
.do(data => ..., err => ...);