THE SITUATION:
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.
THE CODE:
The service:
import { Injectable } from '@angular/core';
@Injectable()
export class LoginService {
public accountInfo;
setUserData(value)
{
this.accountInfo = value;
}
getUserData() {
return this.accountInfo;
}
}
The 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);
The result is undefined
. Probably because this.accountInfo (in the service) is instantiated again when the service is called from the other component...
THE QUESTION:
How can I store some data as a global variable? Can it be done by sharing a service?
Thanks!
Ionic provides a method for storing global variables with the Storage
plugin. (cordova-sqlite-storage
). Storage will attempt to use IndexedDB
, WebSQL
, and localstorage
, in that order.
First add it to the providers list.
In src/app.module.ts
import { Storage } from '@ionic/storage';
@NgModule({
declarations: [
// ...
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: [
Storage
]
})
export class AppModule {}
And then inject it in your component
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);
})
}
}
@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.
And that was the problem because the service was instantiated again and thus public accountInfo
lost his previous content.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With