typescript - 我想在订阅参数之外使用变量
问题描述
我正在使用 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 页面上的任何地方使用,就像在其他功能上一样,我想在页面上全局声明它。我怎样才能做到这一点?
解决方案
制作全局变量的一种简单方法是将其分配给窗口,而不是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'));
}
推荐阅读
- node.js - 开玩笑地模拟复杂依赖项(Papa.parse 的 S3 访问)
- r - tsne 图中的特征可视化
- pandas - Python打包:了解根文件夹,从包文件中导入,
- docker - Docker构建时,Github包抛出错误
- sharepoint - SharePoint 图片库中的批量更新标记
- python - youtube_dl 错误:无法解析 JSON(由 JSONDecodeError('期望值:第 1 行第 1 列(char 0)')引起)
- android - 有没有办法从命令行从传感器获取数据?
- macos - 如何在 macOS 上升级 pgAdmin 4?
- python - 如何使用 PhotoImage 在 python tkinter 中查看图像
- assembly - 攻击实验室第 2 阶段(缓冲区溢出攻击)