2016-12-23 90 views
0

Angular2的新功能。當我啓動我的應用程序時,我的模板顯示connectedfalse。然後控制檯記錄connected to socket.io,但connected在我的模板中仍然顯示爲false。我如何設置事件,以便在連接狀態發生變化時connected將在我的模板中正確讀取?角度2更新模板var?

import {Component, OnInit} from '@angular/core'; 

let io = require('socket.io-client'); 
let socket = io.connect('http://localhost:4300'); 


@Component({ 
    selector: 'my-app', 
    template: require('./app.component.pug'), 

}) 
export class AppComponent implements OnInit{ 
    connected = false; 

    ngOnInit(){ 
     socket.on('connect',()=> { 
      this.connected = true; 
      console.log('connected to socket.io'); 
     }) 
    } 

    getSocketStatus(){ 
     console.log(this.connected); 
    } 
} 

回答

2

你改變可變出角的更新週期。所以你需要手動告訴它,一些事情已經改變了。請參見本作的角度變化檢測http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

這是一個詳細的解釋應該做的伎倆(未經測試)

import {Component, OnInit, NgZone} from '@angular/core'; 

let io = require('socket.io-client'); 
let socket = io.connect('http://localhost:4300'); 


@Component({ 
    selector: 'my-app', 
    template: require('./app.component.pug'), 

}) 
export class AppComponent implements OnInit{ 
    connected = false; 

    constructor(private zone: NgZone) {}; 

    ngOnInit(){ 
     socket.on('connect',()=> { 
      this.zone.run(() => { 
       this.connected = true; 
      }); 

      console.log('connected to socket.io'); 
     }) 
    } 

    getSocketStatus(){ 
     console.log(this.connected); 
    } 
} 
0
constructor(private _cd: ChangeDetectorRef) {}; 

ngOnInit(){ 
     socket.on('connect',()=> { 

      this.connected = true; 
      this._cd.detectChanges() // detect the changes 
      console.log('connected to socket.io'); 
     }) 
    } 

或者修復@沃爾克的回答,您可以運行整個socket.io的功能區:

ngOnInit(){ 
    this.zone.run(() => { 
     socket.on('connect',()=> { 
      this.connected = true; 
      console.log('connected to socket.io'); 
      }) 
    }); 
}