[英]Update template var in angular 2?
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);
}
}
您可以在Angular的更新周期之外更改變量。 因此,您需要手動告訴它某些更改。 有關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);
}
}
constructor(private _cd: ChangeDetectorRef) {};
ngOnInit(){
socket.on('connect', ()=> {
this.connected = true;
this._cd.detectChanges() // detect the changes
console.log('connected to socket.io');
})
}
或者,要解決@Volker的答案,可以在zone中運行整個socket.io的功能:
ngOnInit(){
this.zone.run(() => {
socket.on('connect', ()=> {
this.connected = true;
console.log('connected to socket.io');
})
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.