I have some values that are saved to sqlite storage when a user logs in, and I need those values to be available all over the app.
I've created a service to fetch and store those values, but it's not working because the only way I've been able to figure out how to do this is by getting the values in a promise, which I don't think will return them outside of then().
value1: string;
value2: string;
constructor(
private storage: Storage,
) {
Promise.all([
this.storage.get('value1'),
this.storage.get('value2'),
]).then((result) => {
this.value1 = result[0];
this.value2 = result[1];
});
}
How can I go about getting these values in my service, and then calling them in my pages like so?
this.value1 = this.myService.value1;
Edit: Per Sergey Rudenko's answer, I created a GlobalService and called the code from a page. Here's the code I used.
GlobalService
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class GlobalService {
public value1: string;
constructor(private storage: Storage) {
this.storage.get('value1').then((value) => {
this.value1 = value;
});
}
}
MyPage
import { Component, OnInit } from '@angular/core';
import { GlobalService } from '../../services/global.service';
@Component({
selector: 'app-index',
templateUrl: './index.page.html',
styleUrls: ['./index.page.scss'],
})
export class IndexPage implements OnInit {
public value1: string;
constructor(private global: GlobalService) {
console.log('value1=' + this.global.value1);
// returns: value1=undefined
}