从角度4中的另一个组件更改布尔值 [英] Change Boolean from another component in angular 4

查看:84
本文介绍了从角度4中的另一个组件更改布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Booleans userRights.service 来检查导航点是显示还是隐藏.因此,因此,我想检查登录用户的权限,然后将导航变量设置为 true false .

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.

为此,我有两个组件:我的 navbar.component.ts 和我的 login.component.ts .在我的 navbar.component.ts 里面是这样的布尔值(15)->

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
...

因此,现在用户在我的 login.component.ts 内部登录,并且触发了 onLogin()函数.例如,我正在呼叫我的 userRights.service.userHasRight('canAddHardware'),然后我需要在 navbar.component.ts 内的 Boolean .code>是从我的 userRights.service.userHasRight('canAddHardware')-> true或false

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.

推荐答案

如果该组件不是同级组件,则可以创建这样的消息服务:

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);
}

}

然后从您的login.component.ts中使用以下方法发送消息:

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);
}

在navbar.component.ts中,您可以在ngOnInit中收听该消息,例如:

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;
          }
        });

这篇关于从角度4中的另一个组件更改布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆