visual-studio - NgxLocalStorage 不检索值

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

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

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

我已经研究过这个问题,我相信我走的路是正确的,但出于某种原因,我的 HomeComponent 在 localStorage 中看不到键/值对。但是,在 login() 中设置后,我可以在 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);
                    });
                });

你不能在构造函数之外使用 like this 服务,也不要使用 self 你需要添加'this'。并且在你的构造函数中将 localStorage 前缀为 private 并在 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/

相关文章:

visual-studio - 谷歌代码SVN使用建议

angular - ng-build 上的端口和代理配置

angular - 使用 ngFor 的内联样式背景图像

javascript - 如何在 Golang 中遍历数据并在 Javascript 中使用时创建唯一 ID

javascript - 如何从 Chrome 扩展程序发送更长的电子邮件?

c++ - OpenCV 断言错误 mat.hpp 第 570 行

sql与asp.net的连接问题

c# - Visual Studio 调试器不会加载文件名中带有 `(反引号)的文件中的符号。谁能解释一下?

angular - 如何根据用户角色显示/隐藏元素 Angular 4

html - webshim polyfill localStorage 在 IE6 中未定义