2016-08-05 60 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