【发布时间】:2018-07-04 11:41:57
【问题描述】:
我有一个 Angular 应用程序向本地 API 发出 http 请求,该 API 返回数据库中的所有项目。在向数据库添加另一个项目并每 5 秒刷新一次数据后,首次加载所有数据时加载没有任何问题。我能够获取所有数据并将其记录到控制台。 但问题是 Html 没有更新以反映数据库中新添加的数据。
我在这个问题中读到了类似的问题 Update scope value when service data is changed
但它是 angular 1,经过研究我发现 $scope.apply 应该使用 zone.js 来实现。但到目前为止,似乎没有任何解决方案奏效。
这是我最初从 api 调用项目的构造函数
constructor(
public Data: ProductService,
private _http: HttpModule,
private sanitizer:DomSanitizer,
private chRef: ChangeDetectorRef,
private zone: NgZone
){
this.Data.getProducts().subscribe(data => {
zone.run(() => {
this.items.data=data
console.log(this.items.data);
alert("inside");
for(var i=0;i<this.items.data.length;i++)
this.items.data[i].picture="http://"+this.items.data[i].picture;
this.items.data[i].picture=this.sanitizer.bypassSecurityTrustUrl(this.items.data[i].picture);
console.log("latestest");
});
});
}
这是我每 5 秒刷新一次数据的代码
ngOnInit() {
this.refreshData();
}
private refreshData(): void {
this.zone.run(() => {
this.chRef.detectChanges();
this.postsSubscription = this.Data.getProducts().subscribe(
data => {
this.items.data = data;
this.subscribeToData();
console.log(this.items);
},
function (error) {
console.log(error);
},
function () {
console.log("complete");
}
);
});
}
private subscribeToData(): void {
this.timerSubscription = Observable.timer(5000)
.subscribe(() => this.refreshData());
}
public ngOnDestroy(): void {
if (this.postsSubscription) {
this.postsSubscription.unsubscribe();
}
if (this.timerSubscription) {
this.timerSubscription.unsubscribe();
}
}
Picture of my items not updating because there is already 5 items stored after adding
【问题讨论】:
-
谁能帮帮我?
标签: html angular typescript data-binding zone.js