【问题标题】:How to change value of object in angular如何以角度更改对象的值
【发布时间】:2021-04-10 07:56:34
【问题描述】:

我有这样的服务:

getLastStatus(id): Observable<string> {
        let url_detail = this.apiurl + `/${id}`;
        return this.http.get<any>(url_detail, this.httpOptions).pipe(
            map(data => {
                var status = data['data'].reduce((item, curr) => {
                    return item.id < curr.id ? curr : item;
                }).status.title;

                return status;

            }),
            catchError(this.handleError)
        );
    }


getData(){
        return this.http.get<DataModel[]>(this.apiurl, this.httpOptions).pipe(
            tap(data=> {
                data.map(d=>{
                    this.getLastStatus(d.id).subscribe(s=>{
                        d.status = s;
                    });
                });
            }),
            catchError(this.handleError)
        );
    }

我想从 json 对象的结果中更新状态值。但是,当我像这样订阅 getData() 时,状态的值没有更新。

this.myService.getData().subscribe(data=>{
      console.log(data)
      data.map(d=>{
         console.log("status ", d.status) //value of status not updated
      })
    });

我应该如何处理我的代码?有什么建议吗?

【问题讨论】:

  • 本题不涉及 JSON。 Angular 基础架构负责从 JSON 文本格式到所需的 JavaScript 对象的所有转换。

标签: javascript arrays angular object rxjs


【解决方案1】:

似乎状态是异步获取的。您可以使用 RxJS 高阶映射运算符(如 switchMap)来避免嵌套订阅。而且由于你有一堆 observables 要同时触发,你可以使用 RxJS forkJoin 函数。

我还使用JS destructuring 来保留对象的属性,除了调整或包含status 属性。

试试下面的

getData() {
  return this.http.get<DataModel[]>(this.apiurl, this.httpOptions).pipe(
    switchMap(data =>
      forkJoin(
        data.map(d => 
          this.getLastStatus(d.id).pipe(
            map(status => ({ ...d, d.status: status }))
          )
        )
      )
    ),
    catchError(this.handleError)
  );
}

您还可以参考here 以获取有关switchMap 运算符和forkJoin 函数的更多信息。

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 2020-11-03
    • 2018-06-09
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多