[英]How do I let angular know a custom window event has been fired and requires update checking
我正在使用一个第三方库 ,该库要求我实现自己的事件侦听器。 这是通过实现window.onGoogleYoloLoad = function() { ... }
。 我试图在用户服务文件中像这样实现它:
@Injectable()
export class UserService {
public userCredentials = new EventEmitter<Credentials>();
constructor(){
window.onGoogleYoloLoad = function(credentials){
this.userCredentials.emit(credentials);
}
}
}
然后,我订阅了该活动。 订阅者确实会收到通知,但视图不会得到更新。 就像角度不知道事件发生一样。
回调在Angular区域之外运行。 将回调移动到组件,然后调用ChangeDetectorRef.detectChanges
import { Component, ChangeDetectorRef } from '@angular/core';
@Component(...)
export class MyComponent {
public userCredentials = new EventEmitter<Credentials>();
constructor(
private cd: ChangeDetectorRef,
private userService: UserService
){
window.onGoogleYoloLoad = function(credentials){
this.userService.userCredentials.emit(credentials);
this.cd.detectChanges();
}
}
}
重新输入Angular区域是另一个选择: markForCheck()和detectChanges()有什么区别?
import { Injectable, NgZone } from '@angular/core';
@Injectable()
export class UserService {
public userCredentials = new EventEmitter<Credentials>();
constructor(private zone: NgZone){
window.onGoogleYoloLoad = function(credentials){
this.zone.run(() => {
this.userCredentials.emit(credentials);
})
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.