如何在Angular中将http响应映射到客户端模型类型 [英] How to map http response to client model type in Angular
问题描述
我在客户端中具有这样的模型MyObejct:
I have model MyObejct like this in client:
class MyObject{
id: number;
name: string;
active: boolean;
}
http响应json数据如下:
And the http response json data like this:
[
{
id: "1",
name: "object1",
active: "true",
}
]
http响应是键-值对,所有值类型都是字符串.因此,如何将http响应映射到"MyObject"类型. http get函数是这样的:
The http response is key-value pair, and all the value type is string. So how can I map the http response to 'MyObject' type. The http get function is like this:
getMyObejct(name: string): Observable<MyObject> {
const url = this.url + 'name/' + name;
return this.http.get<MyObject>(url); // This is part I'm confused
}
getAllObjects(): Observable<MyObject[]> {
return this.http.get<MyObject>(this.url); // How to map this reponse to MyObject
}
http响应值都是字符串类型,但是MyObject具有数字和布尔值类型.我该怎么办?
The http response values are all string type, but MyObject has types number and boolean. How can I do that?
推荐答案
这取决于您是否真正需要MyObject的实例,还是只需要具有相同属性的东西.
It depends on whether you truly need an instance of MyObject, or just something with the same properties.
如果只需要具有相同属性的对象,则可以执行以下操作:
If you just need an object with the same properties, you can do:
return this.http.get<MyObject>(url).map( (obj) => {
id: Number(obj.id),
name: obj.name,
active: obj.active === 'true'
});
如果您需要实际的MyObject实例(例如,如果MyObject具有方法),则可以执行以下操作:
If you need an actual MyObject instance (e.g. if MyObject has methods), you can do:
return this.http.get<MyObject>(url).map( (obj) => Object.assign(new MyObject(), {
id: Number(obj.id),
name: obj.name,
active: obj.active === 'true'
}));
这篇关于如何在Angular中将http响应映射到客户端模型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!