0

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

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

组件.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一个.

4

1 回答 1

3

原来我已经在父组件中设置changedetectionstrategy了。onPush而且该消息没有文本字段,而是一个消息,因此即使强制更新也不会产生任何影响。如果有人也有类似的问题,请查找changedetectionstrategy父组件。

于 2016-08-05T10:56:05.230 回答