0

I'd like to create a function returning an observable with a list that I created with several observable. I think I'm very close from the solution as the debugger stop just one step before displaying the list. Here is my code: ts

this.carService.getEveryCar().subscribe((response) => {
    this.cars = response; 
});

service:

getEveryCar(): Observable<any> {
    let cars = [];
    this.getCars()
      .subscribe(response => {
        cars = response.list;
        this.getOneMoreCar.subscribe(
          response =>{
              cars = response.list;
              return of(cars)
        })
      }
   return of(cars);
}

When I debug I get cars declared as empty till the end when the cars array is filled but then my ts file stop calling the service.

What can I do?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Jean
  • 601
  • 1
  • 10
  • 26
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor May 22 '19 at 17:27
  • See the aforementioned suggested duplicate. Asynchronous calls are a common and critical building block in writing/designing an application. It is critical that you understand how to work with asynchronous calls in javascript, and by extension typescript. Understanding these core concepts will help you become a better programmer and also ensure you do not keep "stubbing your toe" on the same problem. – Igor May 22 '19 at 17:28
  • What's `getCars` and `getOneMoreCar`? – mbojko May 22 '19 at 17:29
  • And as a side note If you want to use the response from one observable in a call to another you can also use `switchMap` – Igor May 22 '19 at 17:31
  • You have assigned cars variable twice. One with getCars() response and other with getOneMoreCar() response. Which one you actually want to fill your cars variable with? – emkay May 23 '19 at 19:39

1 Answers1

0

You should not make any subscription in the service. This is the best way to chain observables.

import { of, concatMap } from "rxjs/operators";
...
getEveryCar(): Observable<any> {
    let cars = [];
    return this.getCars()
      .pipe(concatMap(response => {
          cars = response.list;
          return this.getOneMoreCar()
                     .pipe(concatMap(response => of([cars, response.list])));
      }));
}
Luillyfe
  • 6,183
  • 8
  • 36
  • 46