【发布时间】:2018-08-06 16:46:41
【问题描述】:
我正在订阅 Angular 中的一个主题,在值更改时,我正在尝试更改组件中的变量值。在控制台中,该值显示更新,但在视图(HTML)中,它没有。
Service.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 秒后记录标题,但它突然在视图上发生了变化。仅记录值如何在视图上更改它?
【问题讨论】:
-
请发表您的看法
-
@ShakeerHussain 完成
-
我的猜测:
this.title的范围错误。所以this没有引用你的组件。尝试在其中添加一个 console.log 或断点。不太确定,但也许你可以写this.GMapsService.mysubject.subscribe(value => this.title = value); -
你能把
this.GMapsService.getData('dallas, tx', 'austin, tx');的线移到订阅线下面吗?我的意思是,先订阅然后调用函数。 -
我认为你错过了声明访问修饰符例如:公共标题:any = 'app';
标签: angular angular-services angular-components angular-observable