Perform a method after completion of a previous method in Angular

Asked

Viewed 246 times

1

How to make a method to be executed only after the completion of another method? I understand that in Angular we treat asynchronously, that is, a line of code does not necessarily wait for the completion of the previous one to be executed, nor do I want to use a setTimeout() forcing a method to wait a certain time to be executed. Below I have the following code:

intervalo: number = 10;
resultado: number = 0;

  constructor() { }

  ngOnInit() {
  }

  somarValoresIntervalo() {
    for(let x = 1; x < this.intervalo; x++) {
    this.resultado += x;
  }

  imprimirResultadoMultiplicado(){
    this.somarValoresIntervalo();
    console.log(this.resultado*10);
  }

}

I want the console.log() in the print methodResulted() to be executed only after the previous line has been completed (no matter how long it takes). Is there any way to resolve this through Obsevable,?

1 answer

2


To solve your problem you can use a simple callback

  somarValoresIntervalo(callback) {
    for(let x = 1; x < this.intervalo; x++) {
    this.resultado += x;
    }
    callback()
  }

  imprimirResultadoMultiplicado(){
    this.somarValoresIntervalo(() => console.log(this.resultado*10));
  }

Or you can create a Subject to send data.

  import { Subject } from 'rxjs';

  let subject = new Subject<string>();

  somarValoresIntervalo(callback) {
    for(let x = 1; x < this.intervalo; x++) {
    this.resultado += x;
    }
    subject.next(this.resultado);
  }

 subject.subscribe((resultado) => {
   const resultadoMultiplicado = resultado*10;
 });

  • Good Daniel, I’ll do it this way.

  • I used the first scenario, it worked perfectly.

Browser other questions tagged

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