我有一个简单的组件,每隔几秒调用一次REST api并接收一些JSON数据。我可以从我的日志语句和网络流量中看到返回的JSON数据正在改变,并且我的模型正在更新,但是视图没有改变。角度2 - 查看模型更改后不更新
我的组件看起来像:
import {Component, OnInit} from 'angular2/core';
import {RecentDetectionService} from '../services/recentdetection.service';
import {RecentDetection} from '../model/recentdetection';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'recent-detections',
templateUrl: '/app/components/recentdetection.template.html',
providers: [RecentDetectionService]
})
export class RecentDetectionComponent implements OnInit {
recentDetections: Array<RecentDetection>;
constructor(private recentDetectionService: RecentDetectionService) {
this.recentDetections = new Array<RecentDetection>();
}
getRecentDetections(): void {
this.recentDetectionService.getJsonFromApi()
.subscribe(recent => { this.recentDetections = recent;
console.log(this.recentDetections[0].macAddress) });
}
ngOnInit() {
this.getRecentDetections();
let timer = Observable.timer(2000, 5000);
timer.subscribe(() => this.getRecentDetections());
}
}
而我的看法是这样的:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading"><h3>Recently detected</h3></div>
<div class="panel-body">
<p>Recently detected devices</p>
</div>
<!-- Table -->
<table class="table" style="table-layout: fixed; word-wrap: break-word;">
<thead>
<tr>
<th>Id</th>
<th>Vendor</th>
<th>Time</th>
<th>Mac</th>
</tr>
</thead>
<tbody >
<tr *ngFor="#detected of recentDetections">
<td>{{detected.broadcastId}}</td>
<td>{{detected.vendor}}</td>
<td>{{detected.timeStamp | date:'yyyy-MM-dd HH:mm:ss'}}</td>
<td>{{detected.macAddress}}</td>
</tr>
</tbody>
</table>
</div>
我可以从console.log(this.recentDetections[0].macAddress)
的结果是,recentDetections正在更新对象看,但在表视图不会改变,除非我重新加载页面。
我很努力地看到我在这里做错了什么。谁能帮忙?
另一种方法是注入ChangeDetectorRef并调用'cdRef.detectChanges()'而不是'zone.run()'。这可能更有效,因为它不会像'zone.run()'那样在整个组件树上运行变更检测。 –
@MarkRajcok我猜如果你只是改变实例成员,这可能会更有效。对于在Angulars区域以外运行的代码,您如何看待执行例如'this.router.navigate()'的代码(其他组件中有很多副作用)?我想在这里'detectChanges()'可能无法解决这个问题。你怎么看? –
同意。如果您所做的任何更改都是组件及其后代的本地组件,则只使用'detectChanges()'。我的理解是'detectChanges()'将检查组件及其后代,但'zone.run()'和'ApplicationRef.tick()'将检查整个组件树。 –