Angular httpClient returns 属性 对象上不存在
Angular httpClient returns property does not exist on object
constructor(private http: HttpClient) {
}
ngOnInit() {
this.http.get('url').subscribe(data => {
console.log(data);
console.log(data.login);
});
}
}
在这里,我可以在控制台中看到带有登录名的数据,但我收到一条错误消息,指出数据上不存在 属性 登录名。有没有不使用接口的解决方法?因为我要获取的数据量比较大,以后可能还会修改,请问有什么更好的办法吗?
使用时的docs状态HttpClient
...
this.http.get('/api/items').subscribe(data => {
// Read the result field from the JSON response.
this.results = data['results'];
});
In the above example, the data['results']
field access stands out because you use bracket notation to access the results field. If you tried to write data.results
, TypeScript would correctly complain that the Object coming back from HTTP does not have a results
property. That's because while HttpClient
parsed the JSON response into an Object, it doesn't know what shape that object is.
所以您的选择是键入您的回复(我和文档都建议这样做),或者然后使用括号表示法。
键入响应将创建一个 interface/class,您告诉它这是您对请求的期望:
export interface MyResponse {
results: // your type here
}
this.http.get<MyResponse>('/api/items').subscribe(data => {
this.results = data.results;
});
constructor(private http: HttpClient) {
}
ngOnInit() {
this.http.get('url').subscribe(data => {
console.log(data);
console.log(data.login);
});
}
}
在这里,我可以在控制台中看到带有登录名的数据,但我收到一条错误消息,指出数据上不存在 属性 登录名。有没有不使用接口的解决方法?因为我要获取的数据量比较大,以后可能还会修改,请问有什么更好的办法吗?
使用时的docs状态HttpClient
...
this.http.get('/api/items').subscribe(data => { // Read the result field from the JSON response. this.results = data['results']; });
In the above example, the
data['results']
field access stands out because you use bracket notation to access the results field. If you tried to writedata.results
, TypeScript would correctly complain that the Object coming back from HTTP does not have aresults
property. That's because whileHttpClient
parsed the JSON response into an Object, it doesn't know what shape that object is.
所以您的选择是键入您的回复(我和文档都建议这样做),或者然后使用括号表示法。
键入响应将创建一个 interface/class,您告诉它这是您对请求的期望:
export interface MyResponse {
results: // your type here
}
this.http.get<MyResponse>('/api/items').subscribe(data => {
this.results = data.results;
});