Angular 2 - 推送到要使用 *ngFor 显示的数组时出错

Angular 2 - error when pushing to array to be displayed with *ngFor

我想用 *ngFor 在 Angular 2(特别是 Ionic 2)中显示通过 Google 地理编码器收到的项目列表。

地址-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);
      }
    });
  }

地理编码器 returns 成功列出了我在控制台中显示的结果列表,但 Chrome 立即阻止执行并显示以下错误:

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

哪个指向直线

this.addresses.push(results.formatted_address);

我想在模板的 *ngFor 块中显示 formatted_addresses 的列表。 (我不想使用 Googles 的自动完成搜索框)

你需要改变

function (results, status)

(results, status) =>

否则 this 将不会指向 AddressModal 实例,而是指向回调函数本身。

有关详细信息,请参阅 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions