Ionic Http 请求类的对象或变量级联



我正在尝试从api获取值数组并将其加载到类对象并加载它们以进行选择。

我的问题是无法将 http 请求的数据推送到对象

尝试过的可能性

  1. 直接将数据推送到对象,

  2. 存储在临时中,然后推送

我发现很多关于.map的文章和帖子不确定如何使用它,所以试图将JSON转换为数组数据并存储它

下面是我的代码

我正在尝试级联一个选择以加载另一个选择数据。

我的 api Resopnse

{"data":{"data":[{"id":"1","name":"BCA 1"},{"id":"2","name":"BCA 2"},{"id":"3","name":"BCA 3"}],"status":"success","message":"Class Found"}}

我的期望是

从 API 加载此 JSON 数据

{"id":"1","name":"BCA 1"},{"id":"2","name":"BCA 2"},{"id":"3","name":"BCA 3"}

class对象

class: Class[];
temp:any=[];
class Class {
public id: number;
public name: string;
}
this.http.post(link, data).subscribe(
data => {
var obj = JSON.parse(data["_body"]); 
this.temp.push(obj["data"]["data"]);
}, 
error => {
console.log(JSON.stringify(error)); 
});
this.temp.forEach(Data => {            
this.class.push(Data);
});

控制台输出

{data: Array(3), status: "success", message: "Class Found"}
data: Array(3)
0: {id: "1", name: "BCA 1"}
1: {id: "2", name: "BCA 2"}
2: {id: "3", name: "BCA 3"}
length: 3
__proto__: Array(0)
message: "Class Found"
status: "success"
__proto__: Object

如果这不正确,请告诉我,但根据注释,您应该能够通过这样做来获取data数组:

public classArray: Array<Class> = [];
public yourMethod(): void {
this.http.post(link, data).subscribe(
response => {
// Get the body of the response
const body = response.json();
// Get the data array within the data property
const data = body.data.data;
// This should print the data in the console
console.log(data);
// Add the items to the array
this.classArray.push(...data);
// This should print the classArray array in the console
console.log(this.classArray);
},
error => {
console.log(error);
});
}

编辑

您还可以使用map运算符获取请求的正文,如下所示:

import { map } from 'rxjs/operators/map';
// ...
public classArray: Array<Class> = [];
public yourMethod(): void {
this.http.post(link, data)
.pipe(
map(response => response.json())
)        
.subscribe(
body => {
// Get the data array within the data property
const data = body.data.data;
// This should print the data in the console
console.log(data);
// Add the items to the array
this.classArray.push(...data);
// This should print the classArray array in the console
console.log(this.classArray);
},
error => {
console.log(error);
});
}

最新更新