简体   繁体   中英

how to assign the value returned from local storage to a variable for further use

Scenario


method for retrieving data from local storage

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

i want this 'uid' to use in my another methods like a static variable but not in call back.

Or is there any way to retrieve data from local storage not retuned as promise as a workaround for the above approach.

You should use a service to access your local variable if you are going to access it from multiple areas of the application, unless you want to directly call it from the local storage every time. We opted to use a service to interact with our local storage to keep things uniform and the actual methods to access the local storage uniform.

I do prefer to pull variables into the model for the view to access. Maybe it's just my opinion, but I don't like bypassing the model if I don't have to. The below example is how we have it setup but it would work to call the function directly from the template.

Here is an example Local User Service we are currently using in an Angular 4 project.

Service

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');
    }
}

Once you have created the service and imported it into your component, you can use the functions within to grab your variables out of local storage.

Component

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();
    }

}

Then in your template you would access the object like this.

Template

{{ LocalUserObject.username }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM