简体   繁体   中英

Angular2 Oninit with AfterViewInit

  ngOnInit() {
          this.getPointsOfInterest(this.lat, this.lon).subscribe(
(response) => {this.data = response.json();
                this.lat = this.data.lat;
                this.lon = this.data.lon;
                  },
 (error) => console.log(error)
}

 ngAfterViewInit() {
    var src = { lat: this.lat, lng: this.lon }; 
    var map = L.map('map', { zoomControl: false }).setView(src, 14);
}

The data has not been uploaded yet in ngAfterViewInit this.lat and this.lon = undefined.

How to solve?

I think you could subscribe to observe the output of your request, and then do what you need to do with the data

ngOnInit() {
    this.getData();
  }

  getData() {
    this.http.get('/app/data.json')
      .map((res:Response) => res.json())
      .subscribe(
        data => {
            this.data= data;
            // actions with data
        },
        err => console.error(err),
        () => console.log('done')
      );
  }

ngAfterViewInit does not work the way you think it does. Angular calls this method once it initializes child components and the current component view.

At this point, your async request may or may not have finished and returned with data. You cannot assume it will always be ready within ngAfterViewInit

You should use your data within subscribe methods.

For more info, check this url: Life cycle hooks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM