【发布时间】: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