我的组件正确接收到一条消息(如调试器所见),但是未刷新其 View 。在IPC监听器中需要进行任何手动操作吗?
这是我的组件HTML代码:<div>
{{text}}
</div>
这是TypeScript:
import { Component, OnInit } from '@angular/core';
import { ipcRenderer } from 'electron'
@Component({
selector: 'app-receiver',
templateUrl: './receiver.component.html',
styleUrls: ['./receiver.component.scss']
})
export class ReceiverComponent implements OnInit {
text: string;
constructor() { }
ngOnInit() {
ipcRenderer.on('msg', function (event, arg){
this.text=arg;
})
}
}
我希望页面从Electron进程收到的新字符串显示在页面上,但不会发生
最佳答案
IPC的事件处理在 Angular 区域之外运行。该事件不是所谓的“猴子补丁”。您应该在ngZone.run
调用中应用更改。除此之外,您还使用了function
关键字,该关键字使this
上下文更改为该函数,并且无法再访问this
类。使用箭头符号:
constructor(readonly nz: NgZone) { }
ngOnInit() {
ipcRenderer.on('msg', (event, arg) => {
this.nz.run(() => this.text = arg);
});
}
不过不要忘了在
ngOnDestroy
中“取消监听”消息,否则您将在销毁的指令上触发一次detectChanges,而angular不会那样:)
关于angular - View 不会刷新收到的IPC消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54630120/