情况:
在我的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
)。存储将尝试按顺序使用 IndexedDB
、WebSQL
和 localstorage
。
首先将其添加到提供商列表中。
在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/