2016-08-05 61 views
0

我有这个组件(和另一个具有相同问题)。当字段值更改视图不更新时,我甚至试图强制更改检测,但它不起作用。Angular2查看变量更改后没有更新

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

回答

2

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