在我的 Angular-12 应用程序中,我的服务中有以下代码:
constructor(private http: HttpClient, private router: Router) {
var currentUser = JSON.parse(localStorage.getItem('user')|| '{}');
this.token = currentUser && currentUser.token;
}
public getAllCountries(): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, Authorization, Content-Type, Accept",
"Authorization" : "Bearer " + this.token
})
};
return this.http.get(this.apiUrl + '/fetchCountries', httpOptions )
.pipe(
map((response: Response) => {
return response;
})
);
}
突出显示这一行:
<块引用>map((response: Response) => {
<块引用>返回响应;
然后我得到这个错误:
Argument of type 'OperatorFunction<Response, Response>' is not assignable to parameter of type 'OperatorFunction<Object, Response>'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'Response': headers, ok, redirected, status, and 12 more.ts(2345)
如何解决?
谢谢
答案 0 :(得分:0)
您正在使用 Response
,这也是非常不推荐使用的,如果我没记错的话,它在我们使用 Http
时被重新使用,例如 pre angular version 4。 HttpClient
...它返回一个通用对象,就像错误也说的那样。相反,您应该将数据输入到接口并告诉 HttpClient 您正在接收什么。假设你得到一个数组,所以这样的事情应该可以工作:
export interface Country {
// whatever properties your response has
}
然后告诉 HttpClient 您期望的响应是一个 Country
数组。此外,您实际上不需要此处的 map
,因为您没有以任何方式修改数据......所以这就足够了:
return this.http.get<Country[]>(this.apiUrl + '/fetchCountries', httpOptions)
请始终参考官方文档以获取最新文档:https://angular.io/guide/http