-2

Reference: How can I detect service variable change when updated from another component?

Current Behavior: Users login and the menu items does not update when variable values changes in the header component. It only updates when the page is refreshed.

Expected Behavior: Hide menu some of the menu items when user logs in - immediately.

Header component contains menu and subscribed to authentication service:

isAuthenticated: boolean = false;

this.items = [
  {
    title: 'Home',
    link: '/',
    home: true,
  },
  {
    title: 'Dashboard',
    link: '/dashboard',
    hidden: !this.isAuthenticated,
  },
]
ngOnInit() {
    this.authService.isAuthenticated().subscribe(res => this.isAuthenticated = res);
}
Maihan Nijat
  • 7,755
  • 6
  • 40
  • 87
  • At a guess, `isAuthenticated()` only returns a stream of a single value, and doesn't get updated by the `authService` as needed. – jonrsharpe Nov 01 '18 at 12:53
  • @jonrsharpe `isAuthenticated()` is updated when users login or logout. And both login and logout has `ChangeDetectorRef` for detecting changes. – Maihan Nijat Nov 01 '18 at 12:55
  • Then another problem might be that `!this.isAuthenticated` is probably only evaluated once. But give a proper [mcve]. – jonrsharpe Nov 01 '18 at 12:56
  • @jonrsharpe Yes, `!this.isAuthenticated` is updated only once. – Maihan Nijat Nov 01 '18 at 12:57
  • Why did you expect otherwise? If it's outside a method, when *would* it get updated? It's not a magic reference to the `isAuthenticated` property, it's just the value `true`. – jonrsharpe Nov 01 '18 at 13:02
  • @jonrsharpe How to trigger the method which each update? The subscription is also called once. – Maihan Nijat Nov 01 '18 at 13:04
  • You need to recalculate `this.items`. Maybe make it an accessor. – jonrsharpe Nov 01 '18 at 13:04
  • @jonrsharpe I can recalculate that/ or update the `isAuthenticated` but the problem is catching the change in the serivce. I am subscribed to the service but I want to trigger a method each time change in service. – Maihan Nijat Nov 01 '18 at 13:06

1 Answers1

-1

You should use array filter for example

this.authService.isAuthenticated().subscribe(res=>{
    this.isAuthenticated = res
    res.filter(elem=>{
        this.isAuthenticated = res
    }
} );
gabibrk
  • 62
  • 5