Reputation: 10834
I want to display a list of items I received through the Google Geocoder in Angular 2 (specifically Ionic 2) with *ngFor.
address-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>
address-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);
}
});
}
The geocoder returns successfully a list with results, which I display in the console, but Chrome immediately blocks execution and displays the following error:
address-modal.ts:45 Uncaught TypeError: Cannot read property 'addresses' of undefined
which points to the line
this.addresses.push(results.formatted_address);
I would like to display the list of formatted_addresses in my *ngFor block on my template. (I don't want to use Googles' Autocomplete searchbox)
Upvotes: 0
Views: 624
Reputation: 657741
You need to change
function (results, status)
to
(results, status) =>
otherwise this
won't point to the AddressModal
instance but instead to the callback function itself.
For more details see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Upvotes: 1