情况:
在我的app.component中有登录功能.它工作正常,我从API获取用户数据.
我需要将这些数据存储为全局变量,以便能够在整个应用程序中访问它.
我认为共享服务是实现这一目标的方式,但不幸的是,我没有按照我的想法工作.
代码:
服务:
import { Injectable } from '@angular/core';
@Injectable()
export class LoginService {
public accountInfo;
setUserData(value)
{
this.accountInfo = value;
}
getUserData() {
return this.accountInfo;
}
}
Run Code Online (Sandbox Code Playgroud)
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);
});
}
Run Code Online (Sandbox Code Playgroud)
尝试从另一个组件访问用户数据:
this.accountInfo = this.loginService.getUserData();
console.log(this.accountInfo);
Run Code Online (Sandbox Code Playgroud)
结果是undefined.可能是因为当从其他组件调用服务时,再次实例化this.accountInfo(在服务中)...
问题:
如何将一些数据存储为全局变量?可以通过共享服务来完成吗?
谢谢!
@Matt 答案工作正常,它为问题提供了一个很好的解决方案。
我还发现了我的代码中的问题:该服务必须是单例。相反,我将服务注入组件的提供者中。
这就是问题所在,因为服务被再次实例化,因此public accountInfo丢失了以前的内容。
您可以共享一个服务来存储全局变量 - 但必须是单例 - 您只需在 app.module.ts 中注入一次:
providers: [ LoginService ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10505 次 |
| 最近记录: |