New to Angular2. My template shows connected
as false
when I startup my app. Then the console logs connected to socket.io
but connected
still reads false in my template. How can I set things up so that when the connection status changes connected
will read correctly in my template?
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);
}
}
You change the variable out of the update-cycle of Angular. So you need to tell it manually, that something has changed. See this for a detailed explanation of the Angular Change Detection http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
This should do the trick (untested)
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);
}
}
constructor(private _cd: ChangeDetectorRef) {};
ngOnInit(){
socket.on('connect', ()=> {
this.connected = true;
this._cd.detectChanges() // detect the changes
console.log('connected to socket.io');
})
}
Or , to fix @Volker's answer , you can run the whole socket.io's functions in zone :
ngOnInit(){
this.zone.run(() => {
socket.on('connect', ()=> {
this.connected = true;
console.log('connected to socket.io');
})
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.