Sithys
Sithys

Reputation: 3803

Change Boolean from another component in angular 4

I'm using Booleans and a userRights.service for checking whether a nav-point is shown or hidden. So therefore i'd like to check the rights from the user who's logging in, and than set the variables for the navigation to true or false.

I have two components for that: My navbar.component.ts and my login.component.ts. Inside my navbar.component.ts are Booleans (15) like this ->

canAddHardware
canChangeUserRights
canEditBlog
...

So now the user logs in, inside my login.component.ts and the onLogin() function gets triggerd. I'm calling my userRights.service.userHasRight('canAddHardware') for example, and than i need the Boolean inside my navbar.component.ts to be the value which gets returned from my userRights.service.userHasRight('canAddHardware') -> true or false

I tried so many things but i'm not able to figure out how to do this.

Upvotes: 1

Views: 1180

Answers (1)

Mac_W
Mac_W

Reputation: 2987

If this components are not siblings than you can create a message service like this:

export class ShareDataService {
messageSource = new BehaviorSubject<IMessage>({
    messageType: 'message',
    payload: 'something',
});
currentMessage: Observable<IMessage> = this.messageSource.asObservable();
changeMessage(message: IMessage) {
    this.messageSource.next(message);
}

}

Then from your login.component.ts you can then dispatch a message using a method like the below:

    sendMessage(message: MessageType, data: any) {
    const messageToSend: IMessage = {
        messageType: message,
        payload: data,
    };
    this.shareDataService.send(messageToSend);
}

And in your navbar.component.ts you can listen to that message in the ngOnInit for example:

        this.shareDataService.currentMessage.subscribe((message: IMessage) => {
          if (message === 'message') {
              this.canAddHardware = true;
          }
        });

Upvotes: 1

Related Questions