[英]What is the best practice to listening to DOM event in Angular 8?
I want to listening 'storage' event from window in Angular 8. So, what is the best practice to do what below in Angular?我想从 Angular 8 的窗口中收听“存储”事件。那么,在 Angular 中执行以下操作的最佳实践是什么?
window.addEventListener('storage', () => {
});
One way is using Renderer2, but is there a better way?一种方法是使用 Renderer2,但有更好的方法吗?
You can use RxJS for this.您可以为此使用 RxJS。 From the Official documentation ,
从官方文档,
RxJS offers a number of functions that can be used to create new observables.
RxJS 提供了许多可用于创建新 observable 的函数。 These functions can simplify the process of creating observables from things such as events, timers, promises, and so on.
这些函数可以简化从事件、计时器、承诺等事物创建可观察对象的过程。
Also RxJS uses pure functions, which will minimize the risk of errors. RxJS 也使用纯函数,这将最小化错误的风险。
import { Observable, fromEvent } from 'rxjs';
var storage = Observable.fromEvent(window, 'storage').subscribe(res => console.log(res));
you can attach host listener to local storage as Storage interface emits storage event on global objects which it affects.您可以将主机侦听器附加到本地存储,因为 Storage 接口在它影响的全局对象上发出存储事件。
something like this像这样的东西
import { KeyboardEvent } from '@angular/core';
@Component({
...
host: {
'(document:storage)': 'onStorageChange($event)'
}
})
export class MyComponent {
onStorageChange(ev:KeyboardEvent) {
// do something meaningful with it
console.log(`Localstorage change/updated!`);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.