angular - 将 Angular 4 服务重写为 Angular 7 导致 Rxjs 问题
问题描述
我很难将 Angular 4 服务重写为 Angular 7 紧凑型代码
角4代码:
public load(): Observable<Product[]> {
return this.cache<Product[]>(() => this.products,
(val: Observable<Product[]>) => this.products = val,
() => this.http
.get(this.apiUrl + "/products")
.map((response) => response.json()
.map((item) => {
let model = new Product();
model.updateFrom(item);
return model;
})));
}
到目前为止,我尝试通过使用httpClient
而不是重写它以支持 Angular 7 http
:
public all(): Observable<Product[]> {
return this.cache<Product[]>(() => this.products,
(val: Observable<Product[]>) => this.products = val,
() => this.http
.get(this.apiUrl + "/products")
.pipe(map((response: Product) => {
let result: Product[] = [];
let model = new Product();
model.updateFrom(response);
result.push(model);
return result;
}))
);
}
我不确定这是否是正确的方法。查看了文档和其他线程,但找不到答案。请提出你的建议
解决方案
由于您没有提及您有什么问题,我假设您在映射从 HTTP 请求返回的结果时遇到问题。
request返回的结果get
应该是一个数组,需要转换成Product
s的数组。因此它应该是:
...
() => this.http.get(this.apiUrl + "/products")
.pipe(
map((response: Array<any>) => {
let result: Array<Product> = [];
response.forEach((responseModel) => {
let model = new Product();
model.updateFrom(responseModel);
result.push(model);
});
return result;
})
)
...
推荐阅读
- java - 如何在 PDFBox 中使用不同的字体编写多个字符串
- r - 如何在 R 中绘制回归线分析
- laravel - 尝试将 TLD 从 .test 更改为 .dev 后如何恢复 Laravel Valet?
- sql-server - SQL Server Graph:如何识别子图?
- python - 将 Python 与 Google People API otherContacts.copyOtherContactToMyContactsGroup 方法一起使用
- arrays - 仅当在 if 语句颤动中返回多个时才限制为 1
- javascript - @typescript-eslint/no-unused-vars 类型声明中的误报
- html - Bootstrap 4 导航栏内容在打开下拉菜单时移动
- django - 计算字段上的自定义 ModelAdmin 过滤器
- ios - 图片不会上传到firebase存储,swift