[英]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.