You could move the functions to a singleton service and monitor the value using observables. Try the following
Shared service
import { BehaviorSubject, Observable } from 'rxjs'; // <-- included 'Observable' here - with capital 'O'
@Injectable()
export class SharedService {
private addUsuarioSource = new BehaviorSubject<string>('false');
public addUsuario$ = this.addUsuarioSource.asObservable();
constructor() {
this.addUsuario$.subscribe(status => window.localStorage.setItem('addUsuario', status)); // <-- changed 'userStatus' to 'status'
}
getAddUsuario(): Observable<string> { // <-- capital 'O' instead of small 'o'
let userStatus = window.localStorage.getItem('addUsuario');
userStatus = (userStatus === 'false' || userStatus == null) ? 'true' : 'false';
this.addUsuarioSource.next(userStatus);
return this.addUsuario$;
}
}
Navbar component
import { pipe } from 'rxjs';
import { map, take } from 'rxjs/operators';
export class NavbarComponent implements OnInit() {
subscription: any;
ngOnInit() {
if (this.subscription) {
this.subscription.unsubscribe();
}
this.subscription = this.sharedService.getAddUsuario().pipe(take(1)).subscribe(status => {
// this callback will be called only once due to `pipe(take(1))`
// `status` variable with value 'true' or 'false' as string
});
}
}
Another component
this.sharedService.addUsuario$.subscribe(status => {
// this callback will be called each time a new user status is pushed
// `status` variable with value 'true' or 'false' as string
})
I am using BehaviorSubject
to provide a default value. You could use Rxjs Subject
if you do not wish to provide a default value. Explanation for pipe(take(1))
can be found here.
Note: Storing boolean in local storage isn't a good idea. Because you can only store strings and it returns the values as strings. So you cannot do something like *ngIf==="status"
or *ngIf==="!status"
. It would be *ngIf="status === 'true'"
and *ngIf="status === 'false'"
.
Working example: Stackblitz