【问题标题】:I want to use the variable outside the subscribe parameter我想在订阅参数之外使用变量
【发布时间】:2020-12-18 18:27:01
【问题描述】:

我正在使用 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;
  });
}

我想在 .ts 页面上的任何地方都使用this.key,就像在其他函数上一样,我想在页面上全局声明它。我该怎么做?

【问题讨论】:

    标签: typescript ionic-framework angular-ui-router ionic4


    【解决方案1】:

    创建全局变量的一种简单方法是将其分配给窗口,而不是 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'));
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2018-09-19
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多