Ionic 2 - 如何存储全局变量? [英] Ionic 2 - How to store global variable?

查看:30
本文介绍了Ionic 2 - 如何存储全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

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

In my app.component there is the login function. It is working properly and I get the user data from the API.

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

I need to store this data as a global variable to be able to access it throughout the app.

我认为共享服务是实现它的方法,但不幸的是并没有像我想象的那样工作.

I thought that sharing a service was the way to do it, but unfortunately is not working as I thought.

代码:

服务:

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

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

Trying to access the user data from another component:

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

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

The result is undefined. Probably because this.accountInfo (in the service) is instantiated again when the service is called from the other component...

问题:

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

How can I store some data as a global variable? Can it be done by sharing a service?

谢谢!

推荐答案

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

@Matt answer is properly working and it offer a good solution to the problem.

我还发现了我的代码中的问题:服务必须是单例的.相反,我将服务注入到组件的提供者中.

I also found what was the problem in my code: The service had to be a singleton. I was instead injecting the service in the providers of the component.

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

And that was the problem because the service was instantiated again and thus public accountInfo lost his previous content.

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

You can share a service to store a global variable - but has to be a singleton - you need to inject it only once in the app.module.ts:

providers: [ LoginService ]

这篇关于Ionic 2 - 如何存储全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆