0

I have service like this :

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

I want to update value of status from the result of json object. But, when I subscribe getData() like this, the value of status not updated.

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

What's should i do with my code? Any suggestion?

1
  • There is no JSON involved in this question. The Angular infrastructure takes care of all of the conversion from the JSON text format to JavaScript objects needed. Commented Jan 4, 2021 at 14:38

1 Answer 1

1

It appears the statuses are obtained asynchronously. You could avoid nested subscriptions using RxJS higher order mapping operator like switchMap. And since you have a bunch of observables to trigger at once, you could use the RxJS forkJoin function.

I'm also using JS destructuring to retain the properties of the object except to adjust or include the status property.

Try the following

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

You could also refer here for more info on switchMap operator and forkJoin function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.