我在Angular 2中遇到与异步函数绑定的问题。
问题是VK(全局变量)具有带异步功能的API,我尝试将其包装在Observable中。但是当我第一次单击Button时,在视图{{model?.count}}中仍然是空的。只有在第二次点击后,我才能看到请求中的号码。如何解决?
import { Component } from '@angular/core';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'my-app',
template: `
<h1>My First Angular App</h1>
<button (click)="onClickMe()">Receive data</button>
<span>{{model?.count}}</span>
`
})
export class AppComponent {
private data: Observable<any>;
model: any;
onClickMe() {
this.data = new Observable(observer => {
VK.api("friends.get", {user_id: 2888170}, data => observer.next(data.response));
});
let subscription = this.data.subscribe(
model => this.model = model
);
}
}
答案 0 :(得分:0)
这个全局API可能导致一些代码在Angulars区域之外运行,这就是Angular不知道它需要运行变更检测的原因。
明确调用它应该解决这个问题:
export class AppComponent {
private data: Observable<any>;
model: any;
constructor(private cdRef:ChangeDetectorRef) {}
onClickMe() {
this.data = new Observable(observer => {
VK.api("friends.get", {user_id: 2888170}, data => observer.next(data.response));
});
let subscription = this.data.subscribe(
model => {
this.model = model;
this.cdRef.detectChanges();
);
}
}
解决此问题的其他方法是
this.zone.run(...)
与constructor(private zone:NgZone) {}