Angular 2 - 如何访问回调中的变量并将其显示在视图上

时间:2017-04-21 11:21:11

标签: angular typescript

我的角度2代码存在问题。

我想在处理谷歌请求后在我的视图上显示this.restaurants

app.component.ts

constructor(private ps: PlacesService){
}

ngOnInit(){

if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(position => {

        this.location.lat = position.coords.latitude;
        this.location.lng = position.coords.longitude;


        var request = {
            location: this.location,
            radius: '5000',
            types: ['restaurant']
        };

        this.map = new google.maps.Map(document.getElementById('map'), {
          center: this.location,
          zoom: 15
        });

        this.service = new google.maps.places.PlacesService(this.map);

        this.service.nearbySearch(request, (results, status, pagination) => {
            this.restaurants = results;
            console.log(this.restaurants); //logs an array
        });

        console.log(this.restaurants); //undefined

    });

}

}

app.component.html

<div class="container">

<div id="map"></div>

<div>
    <app-search-results [restaurants]="restaurants"></app-search-results>
</div>

app-search-results组件中的循环未运行,因为this.restaurants未定义。

如果这个变量填满了回调的结果,我怎么能访问它?

我希望我能正确解释。

1 个答案:

答案 0 :(得分:1)

这是因为... // undefined在响应到来之前执行。只有在调用传递给nearbySearch的回调时,数据才可用。当您将其分配给this.restaurants时,角度变化检测将更新绑定。如果它没有,那可能是因为nearbySearch做了一些可疑的事情

你可以尝试

constructor(private ps: PlacesService, private cdRef:ChangeDetectorRef){}

...

    this.service.nearbySearch(request, (results, status, pagination) => {
        this.restaurants = results;
        console.log(this.restaurants); //logs an array
        this.cdRef.detectChanges();
        // or this.cdRef.markForCheck();
    });