angular - 如何从 Angular 组件中的函数内部访问变量
问题描述
export class MapsComponent implements OnInit {
@ViewChild('googleMap') gmapElement: any;
map: google.maps.Map;
data = "initialised";
ngOnInit() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(this.gmapElement.nativeElement, {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
directionsService.route({
origin: "terrell hills, tx",
destination: "alamo heights, tx",
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if (String(status) === 'OK') {
directionsDisplay.setDirections(response);
this.data = "I'm modified in directionsService";
/**********************************************************
Here the directions are displaying correctly but `this.data`'s value is not changing. What is the reason?
************************************************************/
} else {
alert('Directions request failed due to ' + status);
}
});
}
}
HTML
<span>{{data}}</span> <!---------Here data is always showing as `initialised`, but directions are displaying perfectly---------->
data
即使使用箭头函数,类成员的值在函数内部也不会改变。的值data
始终显示initialised
。有人可以检查代码中的评论并告诉我答案。
提前致谢。
解决方案
试试这是否有效。
import { ChangeDetectorRef, Component, Input, OnInit } from '@angular/core';
constructor(
private cdr: ChangeDetectorRef
) { }
修改这部分
if (String(status) === 'OK') {
directionsDisplay.setDirections(response);
this.data = "I'm modified in directionsService";
//this.cdr.markForCheck(); // Changed
this.cdr.detectChanges();
} else {
alert('Directions request failed due to ' + status);
}
推荐阅读
- python - 如何使用占位符在 Flask 中编写查询以连接表
- html - ModelForm Django中的ImageField问题,request.FILES为空
- c# - JWT 和 2FA 工作流程
- javascript - 使用两个不同的值作为范围填充 Javascript 中的对象数组
- java - How to Build Graph Using Java Stream API
- python - Odoo api.depends 装饰器问题
- python - 如何在 Python Odoo 中重置 SQL 约束
- console - 如何在 Hetzner Cloud Console 中选择文本?
- javascript - formik 表单值不打印
- css - 使用可滚动的 div 剪辑固定/绝对元素