首页 > 解决方案 > 将 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;
        }))
          );

  }

我不确定这是否是正确的方法。查看了文档和其他线程,但找不到答案。请提出你的建议

标签: angularrxjsangular7

解决方案


由于您没有提及您有什么问题,我假设您在映射从 HTTP 请求返回的结果时遇到问题。

request返回的结果get应该是一个数组,需要转换成Products的数组。因此它应该是:

...

() => 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;
         })
       )

...

推荐阅读