typescript 如何从 Ionic 中的其他页面访问 app.component 变量和方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46414773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the app.component variables and methods from other pages in Ionic?
提问by Dr. X
I want to access and change app.component.ts
variable or access methods from other pages (otherpage.ts
) or other components such as;
我想app.component.ts
从其他页面 ( otherpage.ts
) 或其他组件访问和更改变量或访问方法,例如;
app.component.ts
app.component.ts
@Component({
templateUrl: 'app.html'
})
export class MyApp {
accessedVariable: any;
constructor(){ }
accessedMethod() {
..something
}
}
otherpage.ts
其他页面.ts
@Component({
selector: 'page-other',
templateUrl: './otherpage.html',
})
export class OtherPage {
constructor() { }
}
回答by Sampath
18-02-2020
18-02-2020
Please don't use Event emitter
. Use the Observable
pattern. Otherwise, you'll have to face issues when updating to the Ionic 5. i.e. no Event API on Ionic 5
.
请不要使用Event emitter
。使用Observable
图案。否则,您将不得不在更新到Ionic 5时遇到问题。即没有事件 API Ionic 5
。
Original
原来的
You can do this in a number of ways.
您可以通过多种方式执行此操作。
One method where I can tell you is using Events.
我可以告诉你的一种方法是使用Events。
Events is a publish-subscribe style event system for sending and responding to application-level events across your app.
Events 是一个发布-订阅风格的事件系统,用于在您的应用程序中发送和响应应用程序级事件。
Another method may be using the provider
.On that use case, you can share your methods
and variables
through the provider
.
另一种方法可以使用provider
。对在使用的情况下,你可以分享你methods
和variables
通过provider
。
回答by Rebar
The fastest way is to use a GlobalVarsProvider:
最快的方法是使用GlobalVars提供程序:
install it first with:
首先安装它:
ionic g provider globalvars
this will automatically add the new provider to your app.module.tsfile
这将自动将新的提供程序添加到您的app.module.ts文件中
import {Injectable} from '@angular/core';
@Injectable()
export class GlobalVars {
myGlobalVar: any;
constructor() {
this.myGlobalVar = "";
}
setMyGlobalVar(value) {
this.myGlobalVar = value;
}
getMyGlobalVar() {
return this.myGlobalVar;
}
}
You define there getterand settermethods and the needed variable can be accessed through an Instance of this class! in YourOtherPage.tsyou can get the variable with: this.glVars.getMyGlobalVar()for example.
您定义了getter和setter方法,并且可以通过此类的实例访问所需的变量!在YourOtherPage.ts 中,您可以通过以下方式获取变量:例如this.glVars.getMyGlobalVar()。
here you can read more about it: https://ionicallyspeaking.com/2016/03/10/global-variables-in-ionic-2/
您可以在这里阅读更多相关信息:https: //ionicspeaking.com/2016/03/10/global-variables-in-ionic-2/