如何在Ionic 4中全局访问存储中的值?

时间:2019-01-09 00:39:30

标签: angular ionic-framework

我有一些在用户登录时保存到sqlite存储中的值,我需要这些值在整个应用程序中都可用。

我已经创建了一个用于获取和存储这些值的服务,但是它无法正常工作,因为我能够弄清楚如何做到这一点的唯一方法是通过在promise中获取值,而我没有think会将它们返回到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];
    });
}

我该如何在服务中获取这些值,然后像这样在我的页面中调用它们?

this.value1 = this.myService.value1;

编辑:根据Sergey Rudenko的回答,我创建了GlobalService并从页面调用了代码。这是我使用的代码。

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
    }

1 个答案:

答案 0 :(得分:0)

您需要创建一个共享服务(提供者),每个组件都可以导入和访问公共变量(这使得它们基本上是“全局”的)。

存储是异步的,因此您可能希望将承诺返回的值分配给共享提供程序中的var:

    public globalValue1: string;
    public globalValue2: string;

    constructor(
        private storage: Storage,
    ) {
      this.storage.get('value1').then((value) => { this.globalValue1 = value });
      this.storage.get('value2').then((value) => { this.globalValue2 = value });

    }

然后在您的组件中导入共享提供程序并访问全局变量

更新:

在您的用例中,您似乎正在尝试读取尚未收到分配值的全局变量,这是对Storage的异步调用的一部分。因此,由于组件中的构造方法被称为 before ,因此将分配值-您将看到未定义的值。现在,如果您的用例是要在模板中呈现此类值,则可以使用绑定来防止未定义的值:{{foundation.globalVar? }}-问号将指示该值可能不可用。

我现在知道的在组件构造函数调用时在其中具有值的唯一变通方法-您可能要考虑将数据持久存储在同步存储中-例如浏览器的“本地存储”,但这仅在数据为小。