TypeScript - wait for an observable/promise to finish, and return observable

后端 未结 3 1067
天命终不由人
天命终不由人 2020-12-09 01:59

I am quite new to TypeScript & RxJS, and I am trying to return an Observable after another Observable is finished:

public myObs         


        
相关标签:
3条回答
  • 2020-12-09 02:11

    While flatMap() may work, since you are not passing in a parameter that is used[see param (x)], the best operator for you to use in this scenario is forkJoin().

    Please see this example: https://stackoverflow.com/a/38049268/1742393

       Observable.forkJoin(
        this.http.get('/app/books.json').map((res:Response) => res.json()),
        this.http.get('/app/movies.json').map((res:Response) => res.json())
    ).subscribe(
      data => {
        this.books = data[0]
        this.movies = data[1]
      },
      err => console.error(err)
    );
    
    0 讨论(0)
  • 2020-12-09 02:20

    The problem is that we convert observable into different type... with .subscribe - while we should not (it does not return observable)

    public makeRequest = (): Observable<any> => {
        return this.myObservable().subscribe(
          ... // this is wrong, we cannot return .subscribe
              // because it consumes observable and returns ISusbcriber
        );
    }
    

    When we have an observable... we should just take its result and use .map to convert it to something else

    FlatMap operator

    transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

    public makeRequest = (): Observable<any> => {
        return this.myObservable()
           .flatmap((x) => return this.http
                  .get('http://jsonplaceholder.typicode.com/posts/1')
                  .map( (responseData) => {
                        return responseData.json();
                  })
                  ...
    

    Check all the details here

    TAKING ADVANTAGE OF OBSERVABLES IN ANGULAR 2

    0 讨论(0)
  • 2020-12-09 02:26

    I am looking for this answer some days because this is my problem too. Today I have the answer and would like to share.

    The code is:

    ngOnInit() {
    var idEntidade: number;
    
    this.route.paramMap.subscribe(params => {
      idEntidade = Number(params.get('id'));
    });
    
    this.dataService.getEstados().subscribe(data => {
      this.estados = data;
    });
    
    var dados = this.dataService.getCliente(idEntidade);
    
    **this.subscription = dados.subscribe(
      (data: Cliente) => { this.entityForm.patchValue(data);},
      null,
      () => { this.completed(); }
      );**
    }
    

    and the function completed will be executed after the subscribe is complete.

    completed(){
    let idEstado: number = this.entityForm.controls['estadoId'].value;
    
    if (idEstado === null) {
      return;
    }
    
    this.dataService.getMunicipiosByEstado(this.entityForm.controls['estadoId'].value)
        .subscribe(data => { this.municipios = data; });
    }
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题