首页 > 解决方案 > 我想在订阅参数之外使用变量

问题描述

我正在使用 Ionic 4,我想在文件的任何地方使用该变量。它的使用对我很重要。

我正在使用firebase,我想将一页的一个变量传递到另一页。这个问题就解决了。但我想在第二页的每一部分都使用该变量。

//first page code
joinRoom(key) {
   this.router.navigate(['chat', {key: key}]);
}

//second page code
constructor(public activateroute: ActivatedRoute){
   this.activateroute.params.subscribe((data: any) => {
     console.log(data);
     this.key = data.key;
  });
}

我想this.key在 .ts 页面上的任何地方使用,就像在其他功能上一样,我想在页面上全局声明它。我怎样才能做到这一点?

标签: typescriptionic-frameworkangular-ui-routerionic4

解决方案


制作全局变量的一种简单方法是将其分配给窗口,而不是this.key = data.key你有window.key = data.key

然而,这种方法更像是一种 hack,而不是真正的解决方案

更好的解决方案是拥有某种单例键/值注册表,然后您可以将其注入到您需要的每个组件中

constructor(public activateroute: ActivatedRoute, private configRegistry: CustomRegistry){
   this.activateroute.params.subscribe((data: any) => {
     console.log(data);

     // this.key = data.key;
     configRegistry.set('key', data.key);
  });
}

elsewhere in another file
constructor(private configRegistry: CustomRegistry){
   console.log(configRegistry.get('key'));
}



推荐阅读