【发布时间】:2020-11-05 14:32:58
【问题描述】:
我的代码最初可以正常工作,直到我需要更改 JSON 对象的结构。这是我最初的 JSON 对象结构,它只是我的 API 返回的产品的简单列表。为了简洁起见,我缩写:
[{"PicFile":"11382","ShortDesc":"At Home Slot Machine","ActualPrice":12.99, .... }]
在我的产品服务中,我调用我的 API 并返回一个转换为我的产品模型的列表:
getProductsByCategory(categoryCode: string): Observable<Product[]> {
let url = this.baseAPIUrl + .....
return this.httpClient.get(url)
.pipe(
map((data: any[]) => data.map((item) => this.adapter.convert(item)))
);
}
这是我的适配器代码。我创建了一个可以接受任何类型对象的通用适配器,这就是它的实现:
import { Injectable } from "@angular/core";
import { Adapter } from "./adapter";
export class Product {
constructor(
public PicFile: string,
public ShortDesc: string,
public ActualPrice: number,
.... other properties here
) { }
}
@Injectable({
providedIn: "root",
})
export class ProductAdapter implements Adapter<Product> {
convert(item: any): Product {
return new Product(item.PicFile, item.ShortDesc, item.ActualPrice, .... );
}
}
在我的产品组件中,我订阅了从服务返回的 observable:
loadAllProductsByCategory(categoryCode: string) {
this.loadingSubject.next(true);
this.productService.getProductsByCategory(categoryCode).pipe(
catchError(() => of([])),
finalize(() => this.loadingSubject.next(false))
)
.subscribe(products => this.productsSubject.next(products));
}
这与我的简单 JSON 结构完美配合。我需要为分页目的添加一个计数属性,并且很可能在未来添加其他属性。新的 JSON 对象具有保存产品列表的“Data”属性和称为“Count”的属性。
{"Data":[{"PicFile":"11382","ShortDesc":"At Home Slot Machine","ActualPrice":12.99, ...}], "Count":41}
那么,我的问题是如何更改我的服务代码以查找“数据”属性并进行转换?:
return this.httpClient.get(url)
.pipe(
map((data: any[]) => data.map((item) => this.adapter.convert(item))) <-- how to look for "Data" property and convert only that list, not the whole object?
);
我已经尝试了几件事,包括在此处订阅,但随后它被转换为订阅,我需要返回可观察对象。我确信它可以完成,但我对 Angular 和 RxJS 还很陌生。我似乎无法正确理解映射语法。
提前感谢您提供的任何帮助, 吉姆
【问题讨论】:
-
我不明白为什么你有一个适配器,而你可以订阅 API 并期待一个产品。
-
试试
map((data: any) => data['Data'].map((item) => this.adapter.convert(item)))