简体   繁体   English

Ionic 2 Typescript / Angular2设置全局变量

[英]Ionic 2 typescript/angular2 set global variable

I am new to Ionic and was wondering if there is a way to dynamically set a global variable and then have it for the rest of the app. 我是Ionic的新手,我想知道是否有一种方法可以动态设置全局变量,然后将其用于应用程序的其余部分。

I have an app where on home page I ask user for Phone number and then verify their identity. 我有一个应用程序,该应用程序在主页上要求用户提供电话号码,然后验证其身份。 Once verified I need to store/remember/retrieve for the rest of the app. 验证后,我需要存储/记住/检索其余的应用程序。

Is there a way I can do that rather than passing around it as a parameter? 有什么方法可以代替传递它作为参数吗?

You can use localStorage to save the phone number : 您可以使用localStorage保存电话号码:

 $window.localStorage.setItem("phoneNumber",phoneNumber);
 $window.localStorage.getItem("phoneNumber");

You should be managing your state in a service (ionic calls them providers, generate one with 'ionic generate provider'). 您应该在服务中管理您的状态(ionic将其称为提供程序,并通过“ ionic generate provider”生成一个)。

The official tutorial 'Tour of Heroes' covers this. 官方教程“英雄之旅”涵盖了这一点。 You can find the appropriate section here https://angular.io/docs/ts/latest/tutorial/toh-pt4.html . 您可以在以下网址找到相应的部分:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

basically you create a service: 基本上,您创建服务:

@Injectable()
export class MyService{
  public phoneNumber;
}

and use it from all your components like this: 并从所有组件中使用它,如下所示:

export class MyComponent{
  constructor(private myService: MyService){}

  setPhone(number: number){
    if(validateNumber(number)){
      this.myService.phoneNumber = number;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM