目前我正在使用带有sails.js的angular 2,我遇到了asynchrome事件的问题。 我试图使用promise但是当更新post数组时,视图不会改变,任何人都有想法吗?
谢谢你的回答。
@Injectable()
export class newsService {
posts = [];
constructor() {
console.log('newsService constructor');
io.socket.on('post',event => {
let data = event.data;
switch(event.verb) {
case 'created':
let post = new Post();
post.id = data.id;
post.content = data.content;
post.author = data.author.fullname;
post.date = new Date(data.date);
this.posts.push(post);
break;
}
});
}
}
答案 0 :(得分:1)
我猜套接字确实在Angulars区域外运行,因此Angular不会识别回调并且不会运行变更检测。运行在Angulars区域内更新模型的代码,如:
@Injectable()
export class newsService {
posts = [];
constructor(private zone:NgZone) {
console.log('newsService constructor');
io.socket.on('post',event => {
this.zone.run(() => {
let data = event.data;
switch(event.verb) {
case 'created':
let post = new Post();
post.id = data.id;
post.content = data.content;
post.author = data.author.fullname;
post.date = new Date(data.date);
this.posts.push(post);
break;
}
});
});
}
}