如何在 angular2-localstorage 中设置和获取?
Posted
技术标签:
【中文标题】如何在 angular2-localstorage 中设置和获取?【英文标题】:How to Set & Get in angular2-localstorage? 【发布时间】:2016-12-24 22:41:34 【问题描述】:通过这个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
【问题讨论】:
【参考方案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');
【讨论】:
【参考方案2】:你可以简单地做如下
// 设置在你的任何 ts 文件中
localStorage.setItem('variablekey',value);
// 从任何其他 ts 文件中获取
localStorage.getItem("variablekey");
//如果你想要明确的价值,那么
localStorage.removeItem("variablekey");
【讨论】:
【参考方案3】:我知道它已经得到了回答,但是,这个答案旨在让答案更容易理解。
首先,您需要在主文件中执行此操作:
import LocalStorageService, LocalStorageSubscriber from 'angular2-localstorage/LocalStorageEmitter';
var appPromise = bootstrap(MyRootAppComponent, [ LocalStorageService ]);
// register LocalStorage, this registers our change-detection.
LocalStorageSubscriber(appPromise);
然后SET一个值,在你的组件中,你导入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
要从不同组件的本地存储中GET返回值,请执行以下操作:
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:
【讨论】:
【参考方案4】:该服务仅导入应用程序,以便它可以运行初始化代码。
您应该使用它的方式是通过装饰器作为提到的其他答案。
请注意,这意味着您只需要将服务导入到您的最根 (app) 组件中,而不是所有使用装饰器的组件。
更新
还可以尝试使用instructions 的第2 步中的第一种方式,使用bootstrap
而不是AppComponent
。
不幸的是,这个库正在寻找新的维护者。所以不确定它有多可靠。
【讨论】:
好的,我通过从 WebStorage 导入 LocalStorage 设法将它与装饰器一起使用。 @LocalStorage() 公共用户名:字符串 = 'hello world';但是,我试图从另一个组件调用 @LocalStorage() public username:string,它给了我 null 值,而它实际上应该给 'hello world' 值。 也许太早了,是在构造函数中调用吗?看看它是否在ngOnInit
或 ngAfterViewInit
中工作。
好的,我把它放在 ngOnInit 中,请再次检查我的问题,我已经更新了问题。
该步骤代码的最后一行,特别是LocalStorageSubscriber(appPromise);
好兄弟!像魅力一样工作!【参考方案5】:
看一下GitHub-Page: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;
【讨论】:
好的,当我注入@LocalStorage 注入器时,它给出了这个错误:找不到名称'LocalStorage'。 因为你没有导入它。import LocalStorage from "angular2-localstorage/WebStorage";
好的,导入完成,它正在工作,@LocalStorage() public username:string = '';对于二传手或吸气剂?如何将值设置为用户名?以及如何从用户名中获取值?当我 console.log(this.username) 时,它给了我空值。
在不同的组件中,当我调用 @LocalStorage() public username:string;它给了我空值,即使在我设置为这个的其他组件中:@LocalStorage() public username:string = 'hello world';
我假设它为每个组件(comp1.username,comp2.username,...)单独保存。如果你想让它在所有组件中都可用,你必须创建一个服务。【参考方案6】:
来自文档:
使用 LocalStorage 装饰器
import LocalStorage, SessionStorage from "angular2-localstorage/WebStorage";
class MySuperComponent
@LocalStorage() public lastSearchQuery:Object = ;
@LocalStorage('differentLocalStorageKey') public lastSearchQuery:Object = ;
你在这里:github
【讨论】:
记得从 WebStorage 导入 LocalStorage ;) 通过从 WebStorage 导入本地存储来工作,请重新检查我更新的关于该问题的问题。以上是关于如何在 angular2-localstorage 中设置和获取?的主要内容,如果未能解决你的问题,请参考以下文章