gpt4 book ai didi

javascript - 如何让 Angular 知道自定义窗口事件已被触发并且需要更新检查

转载 作者:行者123 更新时间:2023-11-28 03:49:43 25 4
gpt4 key购买 nike

我正在使用 third-party library这需要我实现我自己的事件监听器。这是通过实现 window.onGoogleYoloLoad = function() { ... } 来完成的。我尝试在我的用户服务文件中像这样实现它:

@Injectable()
export class UserService {
public userCredentials = new EventEmitter<Credentials>();
constructor(){
window.onGoogleYoloLoad = function(credentials){
this.userCredentials.emit(credentials);
}
}
}

然后我订阅了该事件。订阅者确实会收到通知,但 View 不会更新。就像 Angular 不知道事件发生了一样。

最佳答案

回调在 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 区域是另一种选择:What's the difference between markForCheck() and 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);
})
}
}
}

关于javascript - 如何让 Angular 知道自定义窗口事件已被触发并且需要更新检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48108200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com