我在和 Mapbox
在我的Angular项目中,我需要在我的 component.html
从我 component.ts
.
我用的是 mat-vertical-stepper
其中每一步都是一个新的 component
:
<mat-vertical-stepper #stepper>
...
<mat-step [stepControl]="locationStepForm">
<ng-template matStepLabel>Localização</ng-template>
<app-location-step [locationStepForm]="locationStepForm"></app-location-step>
</mat-step>
...
</mat-vertical-stepper>
所以,里面 locationStepForm
我有一张Mapbox地图。为了让地图工作,我把它的初始化放在了 AfterViewInit
方法。
@Input() locationStepForm: FormGroup;
ngAfterViewInit() {
const container = document.getElementById('map');
if (container) {
var map = new Mapboxgl.Map({
container: this.map.nativeElement, // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [-51.186971, -29.1836891], // starting position, LNG/LAT
zoom: 15 // starting zoom
});
}
}
问题是,在某些时候,我需要调用一个函数来更新一个属性,这样它的值就可以通过属性绑定显示在视图中。
@Input() locationStepForm: FormGroup;
latitude: number = 0;
ngAfterViewInit() {
const container = document.getElementById('map');
if (container) {
var map = new Mapboxgl.Map({
container: this.map.nativeElement, // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [-51.186971, -29.1836891], // starting position, LNG/LAT
zoom: 15 // starting zoom
});
geocoder.on('result', function (e) {
geocoder.clear();
this.updateLatitude(e.result.center[1]);
}
}
}
updateLatitude(latitude: number) {
this.latitude = latitude;
}
当 this.updateLatitude(e.result.center[1]);
调用,我得到这个错误。
而如果我直接访问财产。信息不显示 在我 component.html
.
ngAfterViewInit() {
...
geocoder.on('result', function (e) {
...
this.latitude = e.result.center[1];
}
}
这是我的组件.html。
<form [formGroup]="locationStepForm">
<p class="m-l-10">
<span class="text-header">Informe a localização</span>
</p>
<div id="geocoder" class="geocoder"></div>
<div #mapElement id="map" class="map"></div>
<div>
<p>
<span class="text-header">Local selecionado</span>
</p>
<p>
<span>Latitude: {{latitude}}</span>
</p>
<p>
<span>Longitude: {{longitude}}</span>
</p>
</div>
<div>
<button mat-button matStepperPrevious>Retornar</button>
<button mat-button matStepperNext class="button-colored m-l-10">Avançar</button>
</div>
</form>
有什么想法,我做错了什么?
你应该在这部分使用一个箭头函数。
geocoder.on('result', (e) => { //here use arrow function
geocoder.clear();
this.updateLatitude(e.result.center[1]);
}
请注意,如果您使用 function
指的是 this
如果你坚持要用一个 "我 "的名字,那么你就会发现,这个 "我 "的名字已经不一样了。function
而非 arrow function
你应该存储一个对 this
在geocoder.on事件之前的一个变量中。
ngAfterViewInit() {
const container = document.getElementById('map');
var self = this;
if (container) {
var map = new Mapboxgl.Map({
container: this.map.nativeElement, // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [-51.186971, -29.1836891], // starting position, LNG/LAT
zoom: 15 // starting zoom
});
geocoder.on('result', function (e) {
geocoder.clear();
self.updateLatitude(e.result.center[1]);
}
}
}