How to make a function wait another function that has an subscribe with observable in?

Asked

Viewed 1,462 times

0

Next, I have a function that generates a PDF, this function takes a mounted array and mounts a page. After that she requests the next page for the backend through a function with a subscribe.

My problem is that the function does not wait, typescript does not follow a linear flow in code.

Follows a representation in functional blocks for better understanding.

geratePDF() {
  this.GetList();
  this.DesenhaPag();
  this.Page = this.Page ++; 
  this.GetList();
  this.DesenhaPag();
}

Here my function with subscribe.

GetList() {
this.subcription = this.chipservice.listarChip(dadospagechip).subscribe(
  (response) => {

    const listChips = this.chipservice.Validate(response);
    this.montaArraychip(listChips[1], listChips[2]);
    this.subcription.unsubscribe();

  });
}

listarChip(listpage:ListChipsInteface):Observable<any> {
    const token: LoginInteface = this.authService.GetToken();
    return this.http
      .post(`${this.api}/api/user/ChipListHistory/`,[token ,chipvalue])
      .map(res => res.json());
  }

I need to somehow hold PDF until Getlist finishes Mounting Array.

I tried with Promisse I couldn’t, My best solution so far was with async, await and Sleep, but it wasn’t a bad solution, because I’m not sure how long the answer takes.

How would be the ideal solution?

  • Voce can use the mergeMap or switchMap operator

  • You can use rxjs switchMap and chain the observables calls. Nesse link has an example of how to do this chaining.

1 answer

1


Use Subject, it would look something like this:

import { Subject } from 'rxjs';


private listReady = new Subject();

ngOnInit() {
  this.otherSubscription = this.listReady.subscribe(
    () => {
        this.DesenhaPag();
        this.Page = this.Page ++; 
        this.DesenhaPag();
    }
  );
}

GetList() {
this.subcription = this.chipservice.listarChip(dadospagechip).subscribe(
  (response) => {

    const listChips = this.chipservice.Validate(response);
    this.montaArraychip(listChips[1], listChips[2]);
    this.subcription.unsubscribe();

    // aqui sinaliza que está pronto
    this.listReady.next('ready'); // pode ser qualquer objeto como parametro

  });
}

geratePDF() {
  this.GetList();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.