Angular 6 HttpClient 问题映射来自 API 调用的响应
Angular 6 HttpClient Issue with mapping the response from API call
我需要一些关于 Angular 6 HttpClient 的帮助。我对来自 REST API 调用的响应有疑问。我正在使用 HttpClient。我有一个函数可以获取所有用户的列表(在我的例子中我称之为潜在客户)。
fetchLeadsList(){
return this.http.get('http://localhost:3000/api/leads')
.pipe(
map(data => {
console.log(data);
return data;
}));
}
在我的组件的 OnInit
中,我将此端点称为:
this.leadsService.fetchLeadsList()
.subscribe(response => {
console.log(response, 'leadsList');
this.leadsList = response.data; // leadList is declared as an empty array
});
我得到的潜在客户列表如下:
但是,当我尝试映射来自上述组件中提到的服务的响应时 (this.leadsList = response.data),我得到一个错误:
ERROR TS2339: Property 'data' does not exist on type 'Object'.
既然有如图的数据属性,怎么会报错呢?
而且我也可以在视图中显示列表!有什么我想念的吗?
你需要告诉编译器 response
有什么类型。您可以为它创建一个类型或将其设置为 any
让编译器通过您的代码
this.leadsService.fetchLeadsList()
.subscribe((response: any) => {
console.log(response, 'leadsList');
this.leadsList = response.data; // leadList is declared as an empty array
})
HttpClient.get() 方法将 JSON 服务器响应解析为匿名对象类型。它不知道那个物体的形状是什么。
您可以指定要将结果投射到哪个模型:
fetchLeadsList() {
return this.http.get<{ data: any[] }>('http://localhost:3000/api/leads')
^^^^^^^^^^^^^
另请参阅:
尝试访问 response['data'] 希望这能解决您的问题
快乐编码:)
我需要一些关于 Angular 6 HttpClient 的帮助。我对来自 REST API 调用的响应有疑问。我正在使用 HttpClient。我有一个函数可以获取所有用户的列表(在我的例子中我称之为潜在客户)。
fetchLeadsList(){
return this.http.get('http://localhost:3000/api/leads')
.pipe(
map(data => {
console.log(data);
return data;
}));
}
在我的组件的 OnInit
中,我将此端点称为:
this.leadsService.fetchLeadsList()
.subscribe(response => {
console.log(response, 'leadsList');
this.leadsList = response.data; // leadList is declared as an empty array
});
我得到的潜在客户列表如下:
但是,当我尝试映射来自上述组件中提到的服务的响应时 (this.leadsList = response.data),我得到一个错误:
ERROR TS2339: Property 'data' does not exist on type 'Object'.
既然有如图的数据属性,怎么会报错呢?
而且我也可以在视图中显示列表!有什么我想念的吗?
你需要告诉编译器 response
有什么类型。您可以为它创建一个类型或将其设置为 any
让编译器通过您的代码
this.leadsService.fetchLeadsList()
.subscribe((response: any) => {
console.log(response, 'leadsList');
this.leadsList = response.data; // leadList is declared as an empty array
})
HttpClient.get() 方法将 JSON 服务器响应解析为匿名对象类型。它不知道那个物体的形状是什么。
您可以指定要将结果投射到哪个模型:
fetchLeadsList() {
return this.http.get<{ data: any[] }>('http://localhost:3000/api/leads')
^^^^^^^^^^^^^
另请参阅:
尝试访问 response['data'] 希望这能解决您的问题
快乐编码:)