有人可以解释我错过了什么 - 我在OnInit生命周期钩子中为属性变量赋值,但是当尝试在点击事件上再次访问它时,该值消失了:
import {Component} from 'angular2/core';
import {OnInit} from 'angular2/core';
@Component({
selector: 'simple-test',
template: `<button type="button" class="btn btn-primary" (click)="getSearchResults()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search Venues
</button>`
})
export class SimpleTestComponent implements OnInit {
public userLoc: string;
constructor() { }
getSearchResults(){
console.log('userLoc: ' + this.userLoc);
}
ngOnInit() {
this.initGeoLocation();
}
initGeoLocation() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.userLoc = `${position.coords.latitude},${position.coords.longitude}`;
console.log('userLoc: ' + this.userLoc);
});
}
}
}
答案 0 :(得分:3)
首先,你在getCurrentPosition回调函数中丢失了正确的上下文。请改用箭头功能:
initGeoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.userLoc = `${position.coords.latitude},${position.coords.longitude}`;
console.log('userLoc: ' + this.userLoc);
});
}
}
第二个潜在问题。您需要知道地理位置API是异步的,因此如果您太快单击,userLoc
的值可能不可用。在当前位置解决之前,请考虑禁用按钮。
答案 1 :(得分:1)
这是为你的问题工作的plnkr:
http://plnkr.co/edit/uG4rfXySQYWHzlj6iIuj?p=preview
<button type="button" class="btn btn-primary" (click)="initGeoLocation()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search Venues
</button>