是否可以使用角度5中另一个分量中的一个分量的全局变量



我想到的一个问题是:是否可以在一个组件中定义一个全局变量并为其设置值,然后在另一个组件中将其使用。事实上,我知道我可以通过服务来做到这一点,但我想要一种不使用服务的方式,只需要导入或声明或。。。,我不知道。你能帮我吗?这是我的变量,我想在另一个组件中使用它:

export class AdminComponent {
currentUser: any;
isAdvisor: boolean;
constructor() {
this.currentUser = JSON.parse(localStorage.getItem('userInfo'));
if (this.currentUser && this.currentUser.role === 4) {
this.isAdvisorr = true;
}
}
}

提前谢谢你。

您不能只在组件之间共享一个变量,您需要在组件之间使用SharedService进行通信。

如果它只是一个配置,那么您可以将它放在config.ts中,并将其导入两个组件中。

是的,从技术上讲,导出变量是可能的。但在另一个组件中使用该值之前,必须实例化管理组件。

注意最好使用服务

管理组件.ts

export let isAdvisor: boolean;

export class AdminComponent {
currentUser: any;
constructor() {
this.currentUser = JSON.parse(localStorage.getItem('userInfo'));
if (this.currentUser && this.currentUser.role === 4) {
isAdvisorr = true;
}
}
}

其他组件

import {isAdvisorr} from '../admin.component'
//use value here
let advisor = isAdvidorr;

最新更新