我正在做一个示例,该示例是从同一网站上获取的,但是我不知道自己在做错什么,这会给我一个错误,即使我看着它,也看不到我在做什么。我做错了。
执行“ response => response.json()”时,出现以下错误:
json
类型的Object
属性不存在
我的服务如下:
import { Injectable } from '@angular/core';
import { HttpHeaders,HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CompetenceService {
public url: string;
constructor(private httpCliente: HttpClient) {}
public createUser(): Observable < any > {
const getHeaders: HttpHeaders = new HttpHeaders({
'Content-Type': 'application/json'
});
return this.httpCliente
.get('http://xxx/xxx/xxx', {
headers: getHeaders
}).pipe(
map(
response => response.json() < --error: The 'json'
property does not exist in the 'Object'
type
)
);
}
}
有人认为我做错了。
答案 0 :(得分:1)
使用map
时无需HttpClient
。仅当您使用Http
中的@angular/http
时才需要
HttpClient
为您提供实际的响应数据。因此,您不必像在使用json
的情况下那样,就必须在响应中调用Http
来获取实际数据。而且,如果这样做,由于响应数据上将没有名为json
的方法,它将引发错误。这就是它所做的。
摆脱它,你应该就好了。
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CompetenceService {
public url: string;
constructor(private httpCliente: HttpClient) {}
public createUser(): Observable < any > {
const getHeaders: HttpHeaders = new HttpHeaders({
'Content-Type': 'application/json'
});
return this.httpCliente
.get('http://xxx/xxx/xxx', {
headers: getHeaders
});
}
}