Angular 2-模型更改后视图未更新 [英] Angular 2 - View not updating after model changes

查看:91
本文介绍了Angular 2-模型更改后视图未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的组件,该组件每隔几秒钟调用一次REST API,并接收一些JSON数据.从我的日志语句和网络流量中,我可以看到返回的JSON数据正在更改,并且我的模型正在更新,但是视图没有更改.

I have a simple component which calls a REST api every few seconds and receives back some JSON data. I can see from my log statements and the network traffic that the JSON data being returned is changing, and my model is being updated, however, the view isn't changing.

我的组件看起来像:

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)的结果中可以看到,recentlyDetections对象正在更新,但是视图中的表永远不会改变,除非重新加载页面.

I can see from the results of console.log(this.recentDetections[0].macAddress) that the recentDetections object is being updated, but the table in the view never changes unless I reload the page.

我正在努力查看我在这里做错了什么.有人可以帮忙吗?

I'm struggling to see what I'm doing wrong here. Can anyone help?

推荐答案

您的服务中的代码可能会以某种方式超出Angular的区域.这会中断更改检测.这应该起作用:

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

有关调用变更检测的其他方法,请参见在Angular中手动触发变更检测

For other ways to invoke change detection see Triggering change detection manually in Angular

调用变更检测的替代方法是

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

立即为当前组件及其子组件运行更改检测

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

在下一次Angular运行更改检测时包含当前组件

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

对整个应用程序运行更改检测

to run change detection for the whole application

这篇关于Angular 2-模型更改后视图未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆