NgxLocalStorage无法检索值

时间:2017-09-08 03:29:35

标签: visual-studio angular local-storage visual-studio-2017

我正在学习如何使用Ang Studio 2的Visual Studio 2017 SPA模板。

对于本练习,我希望我的HomeComponent在登录AppLoginComponent后显示存储在本地存储(NgxLocalStorage)中的登录用户的名称。 https://www.npmjs.com/package/ngx-localstorage

我已经研究过这个问题,我相信我走的是正确的轨道,但由于某种原因,我的HomeComponent没有在localStorage中看到键/值对。但是,在我在login()中设置后,我可以在Chrome的开发者工具中看到它。

NgxLocalStorage有一个名为get的方法,而不是getItem,但它的工作方式与getItem相同。不幸的是,它没有检索我的价值。

我对Angular 2很新,我确定我在某个地方遗漏了一些东西,请帮助。

我已将NgxLocalStorageModule导入app.module.shared中的NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { NgxLocalStorageModule } from 'ngx-localstorage';

import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { AppLoginComponent } from './components/applogin/applogin.component';
import { FacebookService, FacebookModule } from 'ngx-facebook/dist/esm/index';

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        HomeComponent,
        AppLoginComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'applogin', component: AppLoginComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        FacebookModule.forRoot(),
        NgxLocalStorageModule.forRoot()
    ],
    providers: [FacebookService, NgxLocalStorageModule]
})
export class AppModuleShared {
}

在我的HomeComponent中我有:

import { Component } from '@angular/core';
import { LocalStorageService } from 'ngx-localstorage';

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent {
    currentUser: string;

    constructor(private localStorage: LocalStorageService) {
        this.currentUser = JSON.parse(localStorage.get('currentUser') || '');
    }
}

在AppLoginComponent中我有:

import { Component, NgZone } from '@angular/core';
import { FacebookService, InitParams, LoginResponse } from 'ngx-facebook/dist/esm/index';

import { LocalStorageService } from 'ngx-localstorage';

@Component({
    selector: 'applogin',
    templateUrl: './applogin.component.html'
})
export class AppLoginComponent {

    public loggedIn = false;
    name = "";

    constructor(private _ngZone: NgZone, private fb: FacebookService, localStorage: LocalStorageService) {

        let initParams: InitParams = {
            appId: '123456789',
            xfbml: true,
            version: 'v2.8'
        };

        fb.init(initParams);
    }

    login() {
        var self = this;
        this.fb.login()
            .then((res: LoginResponse) => {
                if (res.authResponse) {
                    this.fb.api('/me')
                            .then((res: any) => {
                                self._ngZone.run(() => {
                                self.name = res.name;
                                self.loggedIn = true;
                                localStorage.setItem('currentUser', res.name);
                        });
                    });
                } else {
                    alert('Not authorized.');
                }
            })
            .catch();
    }

4 个答案:

答案 0 :(得分:4)

我创建了plunker,一切正常。按下登录按钮,它将导航到不同的组件,并在控制台中显示用户与我使用的代码的唯一区别

this.localStorage.set('item', item);
and this.localStorage.get('item');

也在你的代码中

this.fb.api('/me')
                        .then((res: any) => {
                            self._ngZone.run(() => {
                            self.name = res.name;
                            self.loggedIn = true;
                            localStorage.setItem('currentUser', res.name);
                    });
                });

你不能在构造函数之外使用这样的服务而且不要使用self,你需要添加这个'。并在你的构造函数前缀localStorage私有 并在OnInit钩子中做更好的初始化。

    import { Component, NgZone, OnInit } from '@angular/core';
import { FacebookService, InitParams, LoginResponse } from 'ngx-facebook/dist/esm/index';

import { LocalStorageService } from 'ngx-localstorage';

@Component({
    selector: 'applogin',
    templateUrl: './applogin.component.html'
})
export class AppLoginComponent implements OnInit  {

    public loggedIn = false;
    name = "";

    constructor(private _ngZone: NgZone, private fb: FacebookService, private localStorage: LocalStorageService) {


    }

   ngOnInit() {
     let initParams: InitParams = {
            appId: '123456789',
            xfbml: true,
            version: 'v2.8'
        };

        fb.init(initParams);
   }

    login() {
        this.fb.login()
            .then((res: LoginResponse) => {
                if (res.authResponse) {
                    this.fb.api('/me')
                            .then((res: any) => {
                                this._ngZone.run(() => {
                                this.name = res.name;
                                this.loggedIn = true;
                                this.localStorage.set('currentUser', res.name);
                        });
                    });
                } else {
                    alert('Not authorized.');
                }
            })
            .catch();
    }

并在app.module.shared.ts中删除此行

 providers: [FacebookService, NgxLocalStorageModule]

原因forRoot已经导入它们。应该是这样的

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        HomeComponent,
        AppLoginComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'applogin', component: AppLoginComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        FacebookModule.forRoot(),
        NgxLocalStorageModule.forRoot()
    ]
})
export class AppModuleShared {
}

和最后一次

import { FacebookService, FacebookModule } from 'ngx-facebook/dist/esm/index';

尝试使用import without dist

import { FacebookModule } from 'ngx-facebook';

答案 1 :(得分:2)

输入必须是字符串。你可以输入一些模拟数据,如

localStorage.setItem('currentUser', 'TrevorBrooks');

并通过确认已保存项目来检索它。并检查您要发送的数据类型。它是用户对象还是只是名称?

问候

答案 2 :(得分:2)

你应该使用 NgOnInit ,这是解决问题的最佳方法,而不是使用构造函数,因为构造函数用于初始化,依赖注入等等。所以,可能发生的是数据是在您提出要求时尚未提供。除了在npmjs.com页面中,他们清楚地使用ngOnInit添加一个例子,所以我猜他们看到了这个问题。

在您的组件中,执行import { .., OnInit, .. } from '@angular/core';

` 所以你有类似的东西:

import { Component, NgZone, OnInit } from '@angular/core';

并在您的组件导出类中:

export class AppLoginComponent implements OnInit{

ngOnInit() {
   //write your code here
}

答案 3 :(得分:1)

1.确保您已从npm

安装了本地存储模块
npm install --save angular2-localstorage

2.在您的应用模块中导入WebStorageModule:

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

@NgModule({
    import: [WebStorageModule]
@Component({
    providers: [LocalStorageService]
})
export class AppModule {}

2.使用LocalStorage装饰器

从" angular2-localstorage / WebStorage"中导入{LocalStorage,SessionStorage};

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

实施例

@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;
}

查看

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

如需更多说明,请参阅此链接link