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

时间:2016-12-12 14:53:33

标签: ionic2

情况:

在我的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(在服务中)...

问题

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

谢谢!

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:4)

@Matt答案正常运行,它提供了一个很好的解决方案。

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

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

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

providers: [ LoginService ]
相关问题