2016-04-24 65 views
0

我想顯示一個項目列表,這些項目是通過帶有* ngFor的Angular 2(特別是Ionic 2)中的Google Geocoder收到的。Angular 2 - 推送到數組時顯示的錯誤* ngFor

地址modal.html

<ion-content class="address-modal"> 
    <ion-searchbar id="pac" [(ngModel)]="searchQuery" (input)="getItems($event)"></ion-searchbar> 
    <ion-list> 
    <ion-item *ngFor="#address of addresses"> 
     {{ address }} 
    </ion-item> 
    </ion-list> 
</ion-content> 

地址modal.ts

import {Page, NavController, ViewController} from 'ionic-angular'; 
import {ViewChild} from 'angular2/core'; 

declare var google: any; 


@Page({ 
    templateUrl: 'build/pages/address-modal/address-modal.html', 
}) 
export class AddressModal { 

    searchQuery: string = ''; 
    geocoder: any; 
    addresses: any = []; 

    constructor(public nav: NavController, public view: ViewController) { 
    this.geocoder = new google.maps.Geocoder(); 
    } 

    getItems(searchbar) { 

    this.geocoder.geocode({ 'address': searchbar.value }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     console.log('len ' + results.length); 
     console.log(results); 

     for(var i = 0; i < results.length; i++) { 
      this.addresses.push(results.formatted_address); 
     } 

     } else { 
     console.error("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    } 

成功地址解析器返回與結果的列表,這是我顯示在控制檯,但鉻立即塊執行,並顯示以下錯誤:

address-modal.ts:45 Uncaught TypeError: Cannot read property 'addresses' of undefined

指向行

this.addresses.push(results.formatted_address);

我想顯示在我的* ngFor我的模板塊formatted_addresses名單。 (我不希望使用谷歌的搜索框自動完成)

回答