简体   繁体   English

如何设置和获取angular2-localstorage?

[英]How to Set & Get in angular2-localstorage?

From this repo , I've successfully configured this: 从这个回购 ,我已经成功配置了这个:

import {Component} from "angular2/core";
import {LocalStorageService} from "angular2-localstorage/LocalStorageEmitter";

@Component({
    provider: [LocalStorageService]
})
export class AppRoot{
    constructor(private storageService: LocalStorageService){}
...
}

How can I use storageService to set or get in local storage? 如何使用storageService设置或获取本地存储? I can't find example anywhere even in the doc. 即使在doc中我也找不到任何例子。

Updated 更新

After some testing, I've managed it to get it working with Decorator through WebStorage: 经过一些测试,我已经设法让它通过WebStorage与Decorator合作:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class LoginComponent implements OnInit {
   @LocalStorage() public username:string = 'hello world';
     ngOnInit() {
         console.log('username', this.username);
         // it prints username hello world
     }
}

However, when I used Chrome Dev to see my localstorage, I see nothing there: 但是,当我使用Chrome Dev查看我的本地存储时,我什么都没看到: 在此输入图像描述

And In another component, 在另一个组件中,

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class DashboardComponent implements OnInit {
   @LocalStorage() public username:string;
     ngOnInit() {
         console.log(this.username);
         // it prints null
     }
}

The service is imported into the app only so that it can run initialisation code. 该服务仅导入应用程序,以便它可以运行初始化代码。

The way you are supposed to use this is via decorators as other answers mentioned. 你应该使用它的方式是通过装饰器提到的其他答案。

Note that this means you only need to import the service into your root most (app) component only, not all the components that use the decorators. 请注意,这意味着您只需要将服务导入到最根(app)组件,而不是所有使用装饰器的组件。

Update 更新

Also try using the first way in Step 2 of the instructions , using bootstrap instead of AppComponent . 还可以尝试使用指令的第2步中的第一种方法,使用bootstrap而不是AppComponent

Unfortunately this library is looking for a new maintainer. 不幸的是,这个库正在寻找新的维护者。 so not sure how reliable it is. 所以不确定它有多可靠。

i know it's already been answered, however, this answer aims to make the answer easier to understand. 我知道它已经得到了回答,但是,这个答案旨在让答案更容易理解。

First you need to do this in your main file: 首先,您需要在主文件中执行此操作:

import {LocalStorageService, LocalStorageSubscriber} from 'angular2-localstorage/LocalStorageEmitter';
var appPromise = bootstrap(MyRootAppComponent, [ LocalStorageService ]);

// register LocalStorage, this registers our change-detection.
LocalStorageSubscriber(appPromise);

Then to SET a value, in your component, you import WebStorage: 然后在组件中设置一个值,导入WebStorage:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class LoginComponent implements OnInit {
   @LocalStorage('username') public username:string; 
   //username as the parameter will help to use get function
     ngOnInit() {
         this.username = 'hello world';
         console.log('username', this.username);
         // it prints username hello world
     }
}

To GET a value back from the local storage in a different component, do this: 要从其他组件中的本地存储中获取值,请执行以下操作:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class DashboardComponent implements OnInit {
   @LocalStorage('username') public username:string;
   //need to pass your own key parameter to get the value
     ngOnInit() {
         console.log(this.username);
         // it prints 'hello world'
     }
}

Check your chrome dev, you will localstorage is saved: 检查您的chrome dev,您将保存localstorage: 在此输入图像描述

Taking a look at the GitHub-Page: https://github.com/marcj/angular2-localstorage 看一下GitHub-Page: https//github.com/marcmarc/angular2-localstorage

tells us to use it like this way: 告诉我们这样使用它:

Example1 例1

import {LocalStorage} from "angular2-localstorage/WebStorage";

@Component({
    selector: 'app-login',
    template: `
<form>
    <div>
        <input type="text" [(ngModel)]="username" placeholder="Username" />
        <input type="password" [(ngModel)]="password" placeholder="Password" />
    </div>

    <input type="checkbox" [(ngModel)]="rememberMe" /> Keep me logged in

    <button type="submit">Login</button>
</form>
    `
})
class AppLoginComponent {
    //here happens the magic. `username` is always restored from the localstorage when you reload the site
    @LocalStorage() public username:string = '';

    public password:string;

    //here happens the magic. `rememberMe` is always restored from the localstorage when you reload the site
    @LocalStorage() public rememberMe:boolean = false;
}

Example 2 例2

import {LocalStorage} from "angular2-localstorage/WebStorage";

@Component({
    selector: 'admin-menu',
    template: `
<div *ngFor="#menuItem of menuItems() | mapToIterable; #i = index">
    <h2 (click)="hiddenMenuItems[i] = !!!hiddenMenuItems[i]">
        {{i}}: {{category.label}}
    </h2>
    <div style="padding-left: 15px;" [hidden]="hiddenMenuItems[i]">
        <a href>Some sub menu item 1</a>
        <a href>Some sub menu item 2</a>
        <a href>Some sub menu item 3</a>
    </div>
</div>
    `
})
class AdminMenuComponent {
    public menuItems = [{title: 'Menu1'}, {title: 'Menu2'}, {title: 'Menu3'}];

    //here happens the magic. `hiddenMenuItems` is always restored from the localstorage when you reload the site
    @LocalStorage() public hiddenMenuItems:Array<boolean> = [];

    //here happens the magic. `profile` is always restored from the sessionStorage when you reload the site from the current tab/browser. This is perfect for more sensitive information that shouldn't stay once the user closes the browser.
    @SessionStorage() public profile:any = {};
}

UPDATE UPDATE

If you want to use it in all of your components, you need to create a shared service: 如果要在所有组件中使用它,则需要创建共享服务:

import {LocalStorage} from "angular2-localstorage/WebStorage";

@Injectable()
export class MyStorageService {
   @LocalStorage() public username:string = '';
   constructor() {}
}

And use it like this (not copy&paste ready!) 并像这样使用它(不要复制和粘贴准备好!)

export class Component1 {

   private username: string;

   constructor(private _storage: MyStorageService) {
      this.username = this._storage.username;
   }
}

export class Component2 {

   private username: string;

   constructor(private _storage: MyStorageService) {
      this.username = this._storage.username;
   }
}

From documentation: 来自文档:

Use the LocalStorage decorator 使用LocalStorage装饰器

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

class MySuperComponent {
    @LocalStorage() public lastSearchQuery:Object = {};
    @LocalStorage('differentLocalStorageKey') public lastSearchQuery:Object = {};
}

here you are: github 你在这里: github

You can simple do as below 你可以简单地做到如下

// set in any of your ts file //在任何ts文件中设置

localStorage.setItem('variablekey',value);

// get from any other ts file //从任何其他ts文件中获取

localStorage.getItem("variablekey");

// if you want clear value then //如果你想要明确的价值

localStorage.removeItem("variablekey");

I would prefer to create a separate Injectable service 我更愿意创建一个单独的Injectable服务

import { Injectable } from '@angular/core';
@Injectable()
export class LocalStorageService {

    constructor() {
        //
    }

    public setData(key:string, data:any) {
        localStorage.setItem(key, JSON.stringify(data));
    }
    public getData(key:string) {
        return JSON.parse(localStorage.getItem(key));
    }

    public removeData(key:string) {
        localStorage.removeItem(key);
    }
}

And in your component 在你的组件中

import { LocalStorageService } from './../../services/localStorageService';
@Component({
    selector: 'member-claims-modal',
    templateUrl: './view.html'
})

export class UserComponent {
constructor(private localStorageService:LocalStorageService) {
        super();
    }
    public SampleMethod() {
    let cloneData = {
            'claims': 'hello'
        };
    this.localStorageService.setData('claims', cloneData);
    let item=this.localStorageService.getData('claims');
    consoloe.log(item);
    this.localStorageService.removeData('claims');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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