Ionic 2 typescript / angular2设置全局变量

时间:2017-05-19 19:30:33

标签: angular typescript ionic2 global-variables

我是Ionic的新手,想知道是否有办法动态设置全局变量,然后将其用于应用程序的其余部分。

我有一个应用程序,在主页上,我向用户询问电话号码,然后验证他们的身份。一旦验证,我需要存储/记住/检索应用程序的其余部分。

有没有办法可以做到这一点而不是将其作为参数传递?

2 个答案:

答案 0 :(得分:1)

您可以使用localStorage保存电话号码:

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

答案 1 :(得分:1)

您应该在服务中管理您的州(离子称为提供者,使用'离子生成提供者生成一个')。

官方教程'英雄之旅'涵盖了这个。您可以在https://angular.io/docs/ts/latest/tutorial/toh-pt4.html找到相应的部分。

基本上你创建了一个服务:

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

并在所有组件中使用它,如下所示:

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

  setPhone(number: number){
    if(validateNumber(number)){
      this.myService.phoneNumber = number;
    }
  }
}
相关问题