我看到了两种将响应转换为我们的自定义数据模型的方法。
界面
export interface User {
id: number;
name: string;
more_complex_object: // so I am not sure how do this in right way. pass here another interface
//or just a object like {id: '', name: ''}. I show how to do this in class way...
}
Run Code Online (Sandbox Code Playgroud)
并在服务中:
return this.http.get<User>...
Run Code Online (Sandbox Code Playgroud)
没关系,不需要做更多的事情。
班级
export interface Deserializable {
deserialize(input: any): this;
}
export class ComplexModel implements Deserializable {
field1: string;
field2: number;
field3: number;
deserialize(input: any): this {
Object.assign(this, input);
return this;
} …Run Code Online (Sandbox Code Playgroud) 我有一个api,返回像这样的对象/数组:
(2) [{...}, {...}] object
0: {a: '1', b: {id: '1'}}
1: {a: '2', b: {id: '2'}}
Run Code Online (Sandbox Code Playgroud)
所以它看起来像对象的数组(但是debuges说'对象').
所以在我的代码中我有:
return this.http.get(this.url).pipe(
map(datas => {
return datas.map(data => {
let object = {
a: data['a'],
b: data['b']['id'],
}
return object;
})
})
);
Run Code Online (Sandbox Code Playgroud)
但那里:
return datas.map(data => {
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
Property 'map' does not exist on type 'Object'.
Run Code Online (Sandbox Code Playgroud)
但应用程序运行良好是正确显示此数据.但这个错误很烦人.
我能做什么?