I'm using Ngx-webstorage (https://www.npmjs.com/package/ngx-webstorage) annotation to bind properties from local & session storage to typescript variables.
In my app component, the background is defined by one of those properties, called JuegoDatos (Set of data). Each JuegoDatos has a file id, that defines the background image of it.
What i want is, when the JuegoDatos change (sessionStorage property, binded to typescript variable) detect it so i can get the new id of the file and update the background.
I made it work by using an interval.
@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);
}
But it seems a little hacky and very ugly. Also the background flashes.
You need to use BehaviorSubject to detect change.
Create a service like:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class JuegoDatosChangeService {
constructor() { }
public status: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
changeData(value: any) {
this.status.next(value);
}
}
On change of "JuegoDatos", call the service,
this.juegoDatosChangeService.changeData(data);
and to detect the change:
this.juegoDatosChangeService.status.subscribe((val) => {
console.log(val)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With