10

从这个repo,我已经成功配置了这个:

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

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

如何使用 storageService 设置或获取本地存储?即使在文档中,我也无法在任何地方找到示例。

更新

经过一些测试,我设法让它通过 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
     }
}

但是,当我使用 Chrome Dev 查看本地存储时,我什么也看不到: 在此处输入图像描述

在另一个组件中,

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
     }
}
4

6 回答 6

6

该服务仅导入到应用程序中,以便它可以运行初始化代码。

您应该使用它的方式是通过装饰器,就像提到的其他答案一样。

请注意,这意味着您只需要将服务导入到您的最根 (app) 组件中,而不是所有使用装饰器的组件。

更新

还可以尝试使用说明的第 2 步中的第一种方式,使用bootstrap而不是AppComponent.

不幸的是,这个库正在寻找新的维护者。所以不确定它有多可靠。

于 2016-08-18T06:01:00.710 回答
4

我知道它已经得到了回答,但是,这个答案旨在使答案更容易理解。

首先,您需要在主文件中执行此操作:

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

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

然后在你的组件中设置一个值,你导入 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
     }
}

要从不同组件的本地存储中获取值,请执行以下操作:

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

检查您的 chrome 开发人员,您将 localstorage 保存: 在此处输入图像描述

于 2016-08-18T07:14:39.133 回答
3

看看 GitHub 页面:https ://github.com/marcj/angular2-localstorage

告诉我们像这样使用它:

示例 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;
}

示例 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 = {};
}

更新

如果你想在你的所有组件中使用它,你需要创建一个共享服务:

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

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

并像这样使用它(不准备复制和粘贴!)

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;
   }
}
于 2016-08-18T05:54:46.620 回答
1

从文档:

使用 LocalStorage 装饰器

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

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

你在这里:github

于 2016-08-18T05:55:13.607 回答
1

你可以简单地做如下

// 在你的任何 ts 文件中设置

localStorage.setItem('variablekey',value);

// 从任何其他 ts 文件中获取

localStorage.getItem("variablekey");

// 如果你想要明确的值,那么

localStorage.removeItem("variablekey");
于 2017-03-11T11:05:59.333 回答
1

我更愿意创建一个单独的 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);
    }
}

在你的组件中

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');
    }
}
于 2017-11-17T11:21:14.730 回答