【问题标题】:window.onstorage is not working with Angularwindow.onstorage 不适用于 Angular
【发布时间】:2019-07-18 17:25:42
【问题描述】:

我正在尝试创建窗口事件侦听器,该侦听器必须侦听另一个选项卡中的事件,在该选项卡中打开了同一应用程序的另一个实例。
一些服务:

public validateItemAgainstServer = (item: EspApplication) => {
    ...
         window.localStorage.setItem('item', "|")
      ...
    });
  }

组件

constructor(private winRef: WindowRef) {
    winRef.nativeWindow.addEventListener('storage', function (e) {
      console.log("storage event occured");
   }, false);
    window.addEventListener('storage', function (e) {
      console.log("storage event occured");
   }, false);
  }

WinRef

import { Injectable } from '@angular/core';

function _window(): any {
   // return the global native browser window object
   return window;
}

@Injectable()
export class WindowRef {
   get nativeWindow(): any {
      return _window();
   }
}

很遗憾,没有触发 onstorage 事件。是否有可能修复此解决方案,或者对于如何在 Angular 中同步两个选项卡有更好的想法?

【问题讨论】:

标签: javascript angular window-object


【解决方案1】:

Check the live example here!

  @HostListener('window:storage')
  onStorageChange() {
    console.log('change...');
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 2015-01-04
    • 2020-02-11
    • 2019-12-19
    • 2018-06-08
    相关资源
    最近更新 更多