Angular2在变量更改后查看不更新

时间:2016-08-05 10:34:11

标签: angular angular2-changedetection angular2-observables

我有这个组件(另一个有同样的问题)。当字段值更改时,视图未更新,我甚至尝试强制进行更改检测,但它没有工作。

Angular-cli 1.0.0-beta.10
Angular 2.0.0-rc.4

Component.js

import {Component, OnInit, OnDestroy, ChangeDetectorRef} from '@angular/core';
import {Control} from '@angular/common';
import {WebsocketService} from './websocket.service';


@Component({
  moduleId: module.id,
  selector: 'chat',
  template: `<div *ngFor="let message of messages">
                     {{message.text}}
                   </div>
                   <input [(ngModel)]="message"  /><button (click)="sendMessage()">Send</button>`,
  providers: [WebsocketService]
})


export class DummyWebsocketComponent implements OnInit, OnDestroy {
  messages = [];
  connection;
  message;

  constructor(private chatService:WebsocketService, private changeDetector:ChangeDetectorRef) {
  }

  sendMessage() {
    this.chatService.sendMessage(this.message);
    this.message = '';
  }

  ngOnInit() {
    this.connection = this.chatService.getMessages().subscribe(message => {
        this.messages.push(message);
        console.info(this.messages);
        this.changeDetector.markForCheck();
      },
      error => console.error(error),
      () => this.changeDetector.markForCheck()
    );

  }

  ngOnDestroy() {
    this.connection.unsubscribe();
  }
}

chatService.getMessages会返回Observable

1 个答案:

答案 0 :(得分:2)

事实证明我已在父组件中将changedetectionstrategy设置为onPush。并且消息没有文本字段而是消息,因此即使强制更新也不会产生任何影响。如果有人遇到类似问题,也要查找父组件的changedetectionstrategy