【发布时间】:2018-08-02 12:26:44
【问题描述】:
我想知道如何将 json 对象解析为模型并在数组中使用该模型。我尝试了以下方法,但在 Observable 中接收到数据后它对我不起作用:
getExampleData() : Observable<MyModel[]> {
return this.http.get<MyModel[]>( this.exampleGetURL ).pipe(
map((res:Response) => res),
catchError( this.handleError )
);
}
在这里,我尝试记录应该解析为 MyModel[] 的 res 数据,但它仍然是一个 json 对象。
this.myService.getExampleData().subscribe( (res:MyModel[]) => {
console.log(res);
});
这是模型:
export class MyModel {
public name :string;
public price :number;
constructor( name:string, price:number ) {
this.name = name;
this.price = price;
}
public printDetails() {
console.log(this.name);
}
}
遇到这种情况我该怎么办?
更新:
我知道这不是正确的方法,因为我们应该尽可能保持代码干净整洁,但我知道这确实有效:
getExampleData() : Observable<MyModel[]> {
return <Observable<MyModel[]>>this.http.get( this.exampleGetURL ).pipe(
map(res => {
let myModels:MyModel[] = [];
for( let el of <MyModel[]>res )
myModels.push( new MyModel(el.name, el.price) );
return myModels;
}),
catchError( this.handleError )
);
}
有没有办法清理这个烂摊子?
【问题讨论】:
-
你使用的是HttpClient还是HTTP?
-
我正在使用 HttpClient。
-
我刚刚更新了我的帖子。请看截图。
-
首先检查您的 res 并查看它是否包含除结果之外的其他属性,如果您的 res = { 成功:"treu", data: [your response here]} 您必须访问它 map(( res:Response) => res.data
-
@FatehMohamed 我完全按照您所说的进行了尝试,但结果是不确定。
标签: angular http model observable angular6