如何将从本地存储返回的值分配给变量以供进一步使用

时间:2017-08-28 17:43:06

标签: angular ionic2 local-storage

方案

从本地存储中检索数据的方法

 GetFromLocal(){
  this.local.get('uid');
}

我想要这个' uid'在我的另一种方法中使用,比如静态变量但不在回调中。

或者有没有办法从本地存储中检索数据,而不是作为上述方法的解决方法重新作为承诺。

1 个答案:

答案 0 :(得分:0)

如果要从应用程序的多个区域访问本地变量,则应使用该服务访问本地变量,除非您希望每次都直接从本地存储中调用它。我们选择使用服务与本地存储进行交互以保持统一,并且实际访问本地存储的方法均匀。

我更喜欢将变量拉入模型以供访问视图。也许这只是我的意见,但如果我不必,我不想绕过模型。下面的示例是我们如何设置它,但它可以直接从模板调用函数。

以下是我们目前在Angular 4项目中使用的本地用户服务示例。

<强>服务

import { Injectable } from '@angular/core';

// Import Observable Dependencies
import { Observable } from 'rxjs';

export interface LocalUserObject {
    username: string,
    userID: string,
    token: string
}

@Injectable()
export class LocalUserService {

    constructor() { }

    // Get Local User Object from Local Storage
    getLocalUserObject(): LocalUserObject {
        return JSON.parse(localStorage.getItem('CurrentUser') || null);
    }

    // Set Local User Object using the given value.
    setLocalUserObject(localUserObject: LocalUserObject) {
        localStorage.setItem('CurrentUser', JSON.stringify(localUserObject));
    }

    // Destroy the Local User Object.
    destroyLocalUserObject() {
        localStorage.removeItem('CurrentUser');
    }
}

创建服务并将其导入组件后,您可以使用其中的函数从本地存储中获取变量。

<强>组件

import { Component, OnInit, } from '@angular/core';
import { LocalUserService, LocalUserObject } from './_services/local-user.service';

@Component({
    selector: 'users',
    templateUrl: './users.component.html'
})

    export class UsersComponent implements OnInit {

    LocalUserObject: LocalUserObject;

    constructor(
        private _LocalUserService: LocalUserService,
    ) { }

    ngOnInit() {
        this.LocalUserObject = this._LocalUserService.getLocalUserObject();
    }

}

然后在您的模板中,您将像这样访问对象。

<强>模板

{{ LocalUserObject.username }}