我为所有的http调用开发了以下包装类。我刚刚在示例中包含了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:Property&#39; map&#39;类型&#39;订阅错误中不存在。我知道我已经订阅了Observable,如果我摆脱.subscribe()并且只返回函数,它会很好用。但是,我无法在单个层上实现中央错误处理。什么是一个好方法呢?
答案 0 :(得分:4)
类型错误解决了代码中的实际问题。订阅不应该从应该返回可观察的方法返回:
const response$ = this.httpClient.get<T>(...)
response$.subscribe(data => ..., err => ...);
return response$;
除非返回热点可观察效果,否则subscribe
根本不应在服务中执行。相反,do
operator应该用于副作用:
此运算符可用于调试Observables以获取正确的值或执行其他副作用。
注意:这与Observable上的订阅不同。如果没有订阅do返回的Observable,Observer指定的副作用将永远不会发生。因此,只需查看现有的执行,它不会像订阅那样触发执行。
return this.httpClient.get<T>(...)
.do(data => ..., err => ...);
答案 1 :(得分:0)
我可以通过用.do()运算符替换.subscribe()来实现。