以角度2更新模板var?

时间:2016-12-23 21:23:38

标签: angular angular2-template

Angular2新手。当我启动应用时,我的模板会将connected显示为false。然后控制台记录connected to socket.io,但connected在我的模板中仍然显示为false。如何进行设置,以便在我的模板中正确读取连接状态更改connected

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 个答案:

答案 0 :(得分:2)

您可以将变量更改为Angular的更新周期。所以你需要手动告诉它,事情发生了变化。有关角度变化检测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);
    }
}

答案 1 :(得分:0)

constructor(private _cd: ChangeDetectorRef) {};   

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

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

或者,要修复@ Volker的答案,您可以在区域中运行整个socket.io的功能:

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