如何将对象数组映射到我的类型数组 [英] How to map object array to my type array
问题描述
我有一堂课
export class Stuff {
id: string;
namd: string;
}
使用angular < 4.3
我有这个电话:
getStuff(): Observable<Stuff[]> {
return this.http.get('api-url-here/stuff')
.map((data: Response) => {
return data.json()
.map((item: any) => {
return {
id: item.id,
name: item.name
};
});
})
}
使用angular >= 4.3
我将其更改为:
getStuff(): Observable<Stuff[]> {
return this.http.get<Stuff[]>('api-url-here/stuff')
.map((data: any) => {
return data
.map((item: any) => {
return {
id: item.id,
name: item.name
};
});
})
}
我正在从我的api接收到一系列类似的东西.
I am receiving the array of stuff fro my api that looking like that.
[
{"id":1,"name": "name" }
]
我必须两次map
数据两次才能得到我的类型形状(Stuff[]
).是否有更好的方法使用angular 4.3+
做到这一点?
As you can see from the code example above I have to map
the data twice to get my type shape (Stuff[]
). Is there a better way of doing this with angular 4.3+
?
推荐答案
您正在新的HttpClientModule
中使用类型化的响应,因此在第一个map
中,您的结果已被解析.
You are using typed response in new HttpClientModule
, so in first map
your result is already parsed.
getStuff(): Observable<Stuff[]> {
return this.http.get<Stuff[]>('api-url-here/stuff');
}
应该工作.然后
SomeStaffService.getStuff().subscribe(staff => console.log(staff));
更新:
在这种情况下,您将可以通过两种方式处理错误.在您的服务之外
In this case you will be able to handle the errors in two ways. Outside of your service
SomeStaffService.getStuff().subscribe(
staff => console.log(staff),
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {
console.log("Server-side error occured.");
}
}
);
或者您可以直接在您的服务中订阅并在其中捕获错误.请参阅文档
Or you can subscribe right in your service and catch the error there. Please refer to documentation
这篇关于如何将对象数组映射到我的类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!