Javascript 未使用Angular 5使用EventListener更新DOM
上下文:我使用角度PWA通过WKWebview与iOS本机应用程序通信。我使用MessageHandler能够在typescript文件和Swift逻辑代码之间共享数据 问题:我正在使用addEventListener侦听窗口对象上的特定事件。从我的组件中,我订阅了一个可观察到的来倾听变化。但是我的组件没有在subscribe方法中应用变量更改 myService.tsJavascript 未使用Angular 5使用EventListener更新DOM,javascript,angular,typescript,wkwebview,addeventlistener,Javascript,Angular,Typescript,Wkwebview,Addeventlistener,上下文:我使用角度PWA通过WKWebview与iOS本机应用程序通信。我使用MessageHandler能够在typescript文件和Swift逻辑代码之间共享数据 问题:我正在使用addEventListener侦听窗口对象上的特定事件。从我的组件中,我订阅了一个可观察到的来倾听变化。但是我的组件没有在subscribe方法中应用变量更改 myService.ts public myValue$ = new Subject<number>(); window.addEvent
public myValue$ = new Subject<number>();
window.addEventListener('didDeviceDisconnected', (e) => {
...
this.dispatchInfo(someInfo);
});
private dispatchInfo(value: number) {
this.myValue$.next(value);
}
public getValue(): Observable<number> {
return this.myValue$.asObservable();
}
myComponent.html
{{ myValue }}
警报将正确显示该值,但DOM显示该值未定义。我还尝试在subscribe函数中添加setTimeout,但没有成功。如何应用subscribe方法中的更改?它在角度范围之外吗?是的,它在角度范围之外 你可以试试这个 myComponent.ts
// Wait for the notification
this.myValueSubscription = this.myService.getValue().subscribe(value => {
this.myValue = value;
alert("myValue : " + this.myValue);
})
import { Component , NgZone } from '@angular/core';
constructor(public ngZone: NgZone)
this.myValueSubscription = this.myService.getValue().subscribe(value => {
this.ngZone.run(()=> {
this.myValue = value;
});
})
constructor(public ngZone: NgZone)
this.myValueSubscription = this.myService.getValue().subscribe(value => {
this.ngZone.run(()=> {
this.myValue = value;
});
})
我通过使用提供更改检测功能的解决了这个问题
import { Component, ChangeDetectorRef } from '@angular/core';
constructor(.., private cdr: ChangeDetectorRef){}
this.myValueSubscription = this.myService.getValue().subscribe(value => {
this.myValue = value;
alert("myValue : " + this.myValue);
this.cdr.detectChanges(); // <= ADDED
})
从'@angular/core'导入{Component,ChangeDetectorRef};
构造函数(..,私有cdr:ChangeDetectorRef){}
this.myValueSubscription=this.myService.getValue().subscription(值=>{
this.myValue=value;
警报(“myValue:+this.myValue”);
this.cdr.detectChanges();//你确定这个
就是你所认为的吗?如果你控制台.log(这个)呢
就在警报上方
?我猜,此
指的是窗口
,而不是您的组件,因此此.myValue
实际上是窗口。myValue
不起作用,即使我认为这是一种正确的方法,同样的行为也不起作用