我正在使用Ngx-webstoragehttps://www.npmjs.com/package/ngx-webstorage)批注将本地和会话存储的属性绑定到打字稿变量。

在我的应用程序组件中,背景由这些属性之一定义,称为JuegoDatos(数据集)。每个JuegoDatos都有一个文件ID,该文件ID定义了它的背景图像。

我想要的是,当JuegoDatos更改(sessionStorage属性,绑定到typescript变量)检测到它时,我可以获取文件的新ID并更新背景。

我通过使用间隔使其工作。


@SessionStorage(GlobalVariable.JUEGO_DATOS_KEY) private juegoDatosActual: JuegoDatos;

    private idImagen: number;
    private urlImagenJuegoDatos: SafeResourceUrl;

// Some code

ngOnInit() {
        setInterval(() => {
            if (this.juegoDatosActual == null || this.juegoDatosActual.imagenFondo == null) {
                return;
            }
            if (this.idImagen === this.juegoDatosActual.imagenFondo.id) {
                return;
            }

            this.idImagen = this.juegoDatosActual.imagenFondo.id;
            this.reloadImagen();
        }, 1000);
    }



但这似乎有点hacky,非常丑陋。并且背景闪烁。

最佳答案

如果要监视更改,请不要使用@SessionStorage装饰器。注入SessionStorageService并监听发出的更改。

请参阅文档:

https://github.com/PillowPillow/ng2-webstorage#d_sessionStorage

   constructor(private storage:SessionStorageService) {}

    ngOnInit() {
      this.storage.observe('boundValue')
        .subscribe((newValue) => {
          console.log(newValue);
        })
    }

07-24 09:37
查看更多