How to make a function wait for another function that has a subscribe with observable inside?

0

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

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

Following is a representation in functional blocks for a 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 the geratePDF until GetList finishes Assembling the Array.

I tried Promisse I could not, My best solution so far was with async, await and sleep, but it was not a bad solution because I'm not sure how long the response will take.

What would be the ideal solution?

    
asked by anonymous 04.10.2018 / 21:36

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();
}
    
08.10.2018 / 20:56