为了账号安全,请及时绑定邮箱和手机立即绑定

Angular 2-模型更改后视图未更新

Angular 2-模型更改后视图未更新

开满天机 2019-10-15 14:55:41
我有一个简单的组件,该组件每隔几秒钟调用一次REST API,并接收一些JSON数据。从我的日志语句和网络流量中,我可以看到返回的JSON数据正在更改,并且我的模型正在更新,但是视图没有更改。我的组件看起来像: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>从结果中可以看到console.log(this.recentDetections[0].macAddress),recentlyDetections对象正在更新,但是视图中的表永远不会改变,除非我重新加载页面。我正在努力查看我在这里做错了什么。有人可以帮忙吗?
查看完整描述

3 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

就我而言,我有一个非常相似的问题。我正在由父组件调用的函数中更新视图,而在父组件中,我忘记了使用@ViewChild(NameOfMyChieldComponent)。我仅仅因为这个愚蠢的错误而损失了至少3个小时。即:我不需要使用任何这些方法:


ChangeDetectorRef.detectChanges()

ChangeDetectorRef.markForCheck()

ApplicationRef.tick()


查看完整回答
反对 回复 2019-10-15
  • 3 回答
  • 0 关注
  • 864 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信