[英]How do I let angular know a custom window event has been fired and requires update checking
I'm using a third-party library that requires me to implement my own event listener. 我正在使用一个第三方库 ,该库要求我实现自己的事件侦听器。 This is done by implementing
window.onGoogleYoloLoad = function() { ... }
. 这是通过实现
window.onGoogleYoloLoad = function() { ... }
。 I tried to implement it like this in my user service file: 我试图在用户服务文件中像这样实现它:
@Injectable()
export class UserService {
public userCredentials = new EventEmitter<Credentials>();
constructor(){
window.onGoogleYoloLoad = function(credentials){
this.userCredentials.emit(credentials);
}
}
}
Then I subscribed to the event. 然后,我订阅了该活动。 The subscribers do get notified, but the view does not get updated.
订阅者确实会收到通知,但视图不会得到更新。 It's like angular doesn't know the event happened.
就像角度不知道事件发生一样。
The callback is running outside the Angular zone. 回调在Angular区域之外运行。 Move the callback to a component and call
ChangeDetectorRef.detectChanges
将回调移动到组件,然后调用
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();
}
}
}
Re-entering the Angular zone is another option: What's the difference between markForCheck() and 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.