2

I have two requests with the same object result ("Data"). I would get the two responses and put the all in the array ("Data[]"). example :

In my service:

  getData1(): Observable<Data> {
    return this.http
      .get<Data>(`${url}/data`):

  }

  getData2(): Observable<Data> {
    return this.http
      .get<Data>(`${url}/data`):

  }

How I can make for get the result of the two methods and put the all in the data[] for my component?

UPDATE SOLUTION

service

  getData1(): Observable<Data> {
    return this.http
      .get<Data>(`${url}/data`):

  }

  getData2(): Observable<Data> {
    return this.http
      .get<Data>(`${url}/data`):

  }

 getDatas(): Observable<GetData[]> {
   return forkJoin([this.getData1(), this.getData2()]);
  }

component

 getDatas: GetData[];
 ngOnInit() {
    this.dataService.getDatas().subscribe(x =>  this.getDatas= x);
  }

I can make a loop on *ngFor="let data of datas"

It's work

3
  • you can use the forkJoin or merge operators to combine the resulting observables and get the results. Commented Apr 14, 2020 at 18:57
  • 2
    Does this answer your question? How to combine the results of two observable in angular? Commented Apr 14, 2020 at 19:03
  • and, combineLatest is also useful here.. Commented Apr 14, 2020 at 19:05

1 Answer 1

2

Use ForkJoin as below:

 getData(): Observable<Data[]> {
   const req = [];
   req.push(this.http.get<Data>(url_1));
   req.push(this.http.get<Data>(url_2));
   return forkJoin(req);
 }

This will return response as an array where the response of both url will be provided

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.