How to merge or groupBy toPromise via RxJs? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to merge or groupBy toPromise via RxJs? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following method that returns result as shown below:

result: [ { status: 200, ... }, { status: 200, ... }, { status: 400, ... }, ... ]
    

I need to group the result by using status value and return only 2 results instead of 3 for the example result above:

update() {
  this.demoService.update(...).toPromise()
  .then(result => {

    const message = result.map((x: any) => {
      if (x.status === 200) {
        return {
          text: 'successful'
        };
      } else {
        return {
          text: 'fail'
        };
      }
    });

    }
  })
}

I tried to use groupBy of RxJs but I think it cannot be used in Promise. So, how can I group this result in the example above?

Answer

I’m not sure it works, but you can try (you filter only entities with distinct status, then select only statuses):

update() {
  this.demoService.update(...).subscribe(result => {
    const messages = result
        .filter((x, i, arr) => arr.findIndex(t => t.status === x.status) === i)
        .map(x => x.status);

    // do stuff
  });
}
We are here to answer your question about How to merge or groupBy toPromise via RxJs? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji