【问题标题】:Ionic 2 - How to store global variable?Ionic 2 - 如何存储全局变量?
【发布时间】:2016-12-13 17:26:42
【问题描述】:

情况:

在我的 app.component 中有登录功能。它工作正常,我从 API 获取用户数据。

我需要将此数据存储为全局变量,以便能够在整个应用程序中访问它。

我认为共享服务是一种方法,但不幸的是并没有像我想象的那样工作。

代码

服务:

import { Injectable } from '@angular/core';

@Injectable()
export class LoginService {

  public accountInfo;

  setUserData(value) 
  {
    this.accountInfo = value;
  }

  getUserData() {
    return this.accountInfo;
  }

}

app.component:

loginSubmit()
{
    // Function reduced to what is essential to the question

    this.userService.submitLogin(email, password)
        .subscribe((response) => {

            if(response.result == 1) 
            {
                this.loginService.setUserData(response.account_info);

                var justTesting = this.loginService.getUserData();

                // Getting the proper result back
                console.log(justTesting);
            }

        }, (error) => {
            console.log(error);
        });
}

试图从另一个组件访问用户数据:

this.accountInfo = this.loginService.getUserData();
console.log(this.accountInfo);

结果是undefined。可能是因为this.accountInfo(在服务中)在从其他组件调用服务时再次实例化...

问题

如何将一些数据存储为全局变量?可以通过共享服务来完成吗?

谢谢!

【问题讨论】:

  • 在您尝试获取this.accountInfo = this.loginService.getUserData(); 的页面中检查setUserData(value) 中的内容,如果它为空,那么只有它返回未定义,您必须检查设置的用户数据
  • 但是 setUserData 是我为了设置全局变量而调用的函数。
  • 是的,我明白了!只需尝试在您的一个页面中执行this.loginService.setUserData('wellcome');,然后尝试在另一个页面中获取值,例如this.loginService.getUserData();,我相信它会被打印出来。
  • 是的,经过测试并且可以正常工作。
  • 这意味着你可以调用`this.loginService.getUserData();`任何你的组件在你将setuserdata的值设置为null之前它都会工作

标签: ionic2


【解决方案1】:

Ionic 通过Storage 插件提供了一种存储全局变量的方法。 (cordova-sqlite-storage)。存储将尝试按此顺序使用IndexedDBWebSQLlocalstorage

首先将其添加到提供者列表中。

src/app.module.ts

import { Storage } from '@ionic/storage';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    // ...
  ],
  providers: [
    Storage
  ]
})
export class AppModule {}

然后将其注入到你的组件中

import { Storage } from '@ionic/storage';

export class MyApp {
  constructor(storage: Storage) {

     // set a key/value
     storage.set('name', 'Max');

     // Or to get a key/value pair
     storage.get('name').then((val) => {
       console.log('Your name is', val);
     })
  }
}

【讨论】:

  • 谢谢!我发现我的代码有什么问题。该服务不是单身人士。但我也测试了你的解决方案,效果很好!只有一个问题:存储基本上是 ionic 1 的 localStorage 是什么?那么这样,当应用程序关闭时,数据也会被保留,对吧?
  • 在原生应用程序上下文中运行时,Storage 将优先使用 SQLite,因为它是最稳定和广泛使用的基于文件的数据库之一,并避免了 localstorage 和 IndexedDB 之类的一些陷阱,例如操作系统决定在磁盘空间不足的情况下清除此类数据。
【解决方案2】:

@Matt 答案正常工作,它为问题提供了一个很好的解决方案。

我还发现了我的代码中的问题:服务必须是单例的。我是在组件的提供者中注入服务。

这就是问题所在,因为服务被再次实例化,因此public accountInfo 丢失了他之前的内容。

你可以共享一个服务来存储一个全局变量——但必须是一个单例——你只需要在 app.module.ts 中注入一次:

providers: [ LoginService ]

【讨论】:

  • 这是 Angular(和 Ionic)的方法,所以它应该是最受好评的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2021-10-12
  • 2021-09-18
  • 1970-01-01
相关资源
最近更新 更多