constructor(private http: HttpClient) {
}
ngOnInit() {
this.http.get('url').subscribe(data => {
console.log(data);
console.log(data.login);
});
}
}
在这里,我可以在控制台中看到带有登录名的数据,但我收到一条错误消息,指出数据上不存在属性登录名。有没有不使用接口(interface)的解决方法?因为我要获取的数据量比较大,以后可能还会修改,请问有什么更好的办法吗?
最佳答案
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)/类,您告诉它这是您对请求的期望:
export interface MyResponse {
results: // your type here
}
this.http.get<MyResponse>('/api/items').subscribe(data => {
this.results = data.results;
});
关于Angular httpClient返回对象上不存在的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47075175/