S
S
sdgroup142018-04-18 11:28:59
Angular
sdgroup14, 2018-04-18 11:28:59

How to make a function wait for another Angular 2+ function to execute?

In general, as I understand it, I can’t understand how promises work at all ... and what should I do in my situation. Now it works but incorrectly... I would like to remove setTimeout from the function and make it adequate. Please help me figure this out. Essence of the question. How to make the mapReady function wait for buildMarkers to execute

buildMarkers(cars): void {
    for (let i in cars) {
      let lat: number = cars[i].coordinates.lat;
      let lon: number = cars[i].coordinates.lon;
      let pin = cars[i].pin;
      let singleMarker = new Marker([lat, lon], {
        icon: new DivIcon({
          className: 'my-div-icon',
          html: this.getHtmlMarker(cars, pin)
        })
      });
      this.layers.push(singleMarker);
    };
  };

  public mapReady(map) {
    this.map = map;
    let that = this;
    setTimeout(() => {
      that.buildMarkers(this.cars);
    }, 500);
  };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Mazhekin, 2018-04-18
@sdgroup14

Promises to use in the second Angular are trash, you need to relearn the style of the second Angular, the developers of Angular 2+ have already included rxjs in the framework and abandoned promises.

buildMarkers(cars): void {
  return Observable.create(observer => {
    for (let i in cars) {
      let lat: number = cars[i].coordinates.lat;
      let lon: number = cars[i].coordinates.lon;
      let pin = cars[i].pin;
      let singleMarker = new Marker([lat, lon], {
        icon: new DivIcon({
          className: 'my-div-icon',
          html: this.getHtmlMarker(cars, pin)
        })
      });
      this.layers.push(singleMarker);
    };
    
    observer.next();
    observer.complete()
  });
};

public mapReady(map) {
    this.map = map;
    let that = this;

    that.buildMarkers(this.cars).subscribe(() => {
      // тут выполните код, который гарантированно выполнится после buildMarkers
    });
   
  };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question