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

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

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

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

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

最佳答案

我创建了 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 你需要添加'this'。并在您的构造函数中使用 private 前缀 localStorage
并在 OnInit 钩子(Hook)中更好地进行初始化。
    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';

尝试在没有 dist 的情况下使用 import
import { FacebookModule } from 'ngx-facebook';

关于visual-studio - NgxLocalStorage 不检索值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46108176/

10-10 20:17