Avoiding nesting subscriptions in Angular 2+?

后端 未结 3 973
青春惊慌失措
青春惊慌失措 2020-11-30 14:59

I have 2 endpoints:

  • 1 endpoint to get current user logged.
  • 1 endpoint to get grants of this user.

Actually I use:



        
3条回答
  •  攒了一身酷
    2020-11-30 15:35

    Thank you guys. Its working with switchMap.

    import { Component, VERSION, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { switchMap } from 'rxjs/operators';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements OnInit {
      name = 'Angular ' + VERSION.major ;
    
      constructor(private http: HttpClient) {
      }
    
      ngOnInit() {
        this.http.get("https://pokeapi.co/api/v2/pokemon?limit=100&offset=200")
          .pipe(
            switchMap((mp) => {
              console.log("Requisição 01", mp);
              return this.http.get("https://pokeapi.co/api/v2");
            }),
            switchMap((it) => {
              console.log("Requisição 02", it);
              return this.http.get("https://pokeapi.co/api/v2/pokemon/206/");
            })
          )
          .subscribe((d) => console.log("subscribe", d))
      }
    }
    

提交回复
热议问题