我正在订阅 Angular 中的一个主题,在值更改时,我正在尝试更改组件中的变量值。在控制台中,该值显示更新,但在视图(HTML)上,它没有。
服务.ts
export class GMapsService {
public mysubject: Subject<any> = new Subject();
getData(or, des) {
var origin1 = or;
var destinationA = des;
var service = new google.maps.DistanceMatrixService();
var self = this;
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA],
travelMode: 'DRIVING',
avoidHighways: false,
avoidTolls: true,
},
(response, status) => {
// this.mysubject.next(response);
setInterval(
function () {
self.mysubject.next(Math.random())
},
2000
)
}
);
}
}
app.component.ts
export class AppComponent implements OnInit {
title: any = 'app';
constructor(private GMapsService: GMapsService) { }
ngOnInit() {
this.GMapsService.getData('dallas, tx', 'austin, tx');
this.GMapsService.mysubject.subscribe((value) => {
this.title = value;
console.log(this.title);
//title is random number in console. ex: 0.4333333
//title is still 'app' on view till now.
});
setTimeout(() => {
console.log(this.title);
}, 5000);
//title is random number in console. ex: 0.4333333
// title suddenly become 'random number ex: 0.4333333' on view after it is logged after 5 secs. How does logging 'title' again after 5 seconds change its value?
}
}
app.component.html
{{title}}
我相信,如果相同的值在控制台中发生变化,它也应该反映在视图部分。在其他问题上,它说,我错过了这个上下文,但是控制台中的值正在更新,所以我相信我没有错过这个上下文。
编辑:我在 5 秒后尝试记录标题,它突然在视图上改变。仅记录值如何在视图上更改它?