2016-12-23 87 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'); 
      }) 
    }); 
}