Home > Enterprise >  Wait for NgOnInit to complete inside ngAfterViewInit
Wait for NgOnInit to complete inside ngAfterViewInit

Time:05-23

I am loading some data in ngOnInit that I need to access inside of ngAfterViewInit. Specifically, Google Maps API, where I'm loading GPS coordinates from the database, then I need to add them to the map upon creation. I'm creating the map itself in ngAfterViewInit.

I guess I could move the whole thing to AfterViewInit, but I thought I'd ask if there's a good way to wait for ngOnInit to finish before using the data in AfterViewInit, in case I need it in the future for other projects.

ngOnInit() {
  this.loadGpsCoordinates();
}

ngAfterViewInit() {
    var elem = document.getElementById('map');
    if (elem != null) {
    this.map = new google.maps.Map(elem, {
      center: { lat: -32.3881373, lng: 55.4343223 },
      zoom: 17,
      disableDefaultUI: true
    });

    // Now loop through GPSCoordinates to add Markers
    // But wait! What if the coords aren't loaded yet?!
    ...
}

CodePudding user response:

I'm assuming this.loadGpsCoordinates(); returns an Observable (if not it could be made to do so)

private coordinatesSubject = new ReplaySubject<any>(1)

ngOnInit() {
  this.loadGpsCoordinates().pipe(
    tap( data => this.coordinatesSubject.next(data))
  ).subscribe()
}

private ngAfterViewInit(data) { 
 
 this.coordinatesSubject().subscribe( data => {
    // data would be use below
    var elem = document.getElementById('map');
    if (elem != null) {
      this.map = new google.maps.Map(elem, {
        center: { lat: -32.3881373, lng: 55.4343223 },
        zoom: 17,
        disableDefaultUI: true
      });
     }
  })
}

Note: I didn't add a takeUntil(destroyed$) but you can look that up separately - it's used for unsubscribing from the service when the component is removed

  • Related