0

Let us assume that I want to fetch data in my Angular application by calling a REST API in order to display it in the Angular application.

I would call something like this:

this.http.get(this.configUrl).subscribe(response => {
  //do something
});

However, I often have the case that I have to fetch further data based on the first REST API call.So I have something that looks like this:

  this.http.get(this.configUrl).subscribe(response => {
      //next call
      this.http.get(this.configUrl).subscribe(response => {
        //next call
        this.http.get(this.configUrl).subscribe(response => {
          //next call
          this.http.get(this.configUrl).subscribe(response => {
           //do something
           });
         });
      });
    });

I find this very difficult to read. Is there a way to make this more readable in Angular / Typescript or am I doing something fundamentally wrong?

OPunktSchmidt
  • 671
  • 1
  • 9
  • 25

1 Answers1

2

You could use RxJS operators such as switchMap and pipe to streamline this nested call;

    this.http.get(this.configUrl)
      .pipe(map(
        res => res.json()),
        switchMap(data => {
          const data1 = data.sample_datum;
          return this.http.get(this.configUrl + "&data=" + data1);
        }),
        switchMap(data => {
          const data2 = data.sample_datum2;
          return this.http.get(this.configUrl + "&data=" + data2);
        }),
        switchMap(data => {
          const data3 = data.sample_datum3;
          return this.http.get(this.configUrl + "&data=" + data3);
        }),
        switchMap(data => {
          const data4 = data.sample_datum4;
          return this.http.get(this.configUrl + "&data=" + data4);
        }))
      .subscribe((d) => console.log("subscribe", d))

or ou can use the await keyword to prevent nesting.

    const data1 = await this.http.get(this.configUrl);
    const data2 = await this.http.get(this.configUrl + "&data=" + data1);
    const data3 = await this.http.get(this.configUrl + "&data=" + data2);
    const data4 = await this.http.get(this.configUrl + "&data=" + data3);

Onur Özkır
  • 559
  • 3
  • 12