ionic2 - Ionic 2 - 如何存储全局变量?

标签 ionic2

情况:

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

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

我认为共享服务是实现这一目标的方法,但不幸的是它并不像我想象的那样有效。

代码:

服务:

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

@Injectable()
export class LoginService {

  public accountInfo;

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

  getUserData() {
    return this.accountInfo;
  }

}

应用程序组件:

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);

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

问题:

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

谢谢!

最佳答案

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 {}

然后将其注入(inject)到您的组件中

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);
     })
  }
}

关于ionic2 - Ionic 2 - 如何存储全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103557/

相关文章:

javascript - 如何从 ionic radio 基团中获取选定的值

angular - 汇总和 Redux : "index.js does not export default"

ionic-framework - 在 ionic 2 中创建连接时出现 typeorm 问题

javascript - 无法获取 View 中的对象属性

css - Angular/Ionic NGClass 没有做任何事情

ionic-framework - 将图标添加到 ionic 选择中的 ionic 选择中

ionic-framework - ionic 3.X : virtual scroll with infinite scroll(i. e 改变数据集)

angular - 如何在 ionic2 中调整项目分隔符的大小

angular - 如何使用 float 标签进行 ionic 选择

angular - Ionic2 中的登录验证