【问题标题】:NgxLocalStorage Doesn't Retrieve ValueNgxLocalStorage 不检索值
【发布时间】:2018-02-16 21:21:45
【问题描述】:

我正在学习如何使用适用于 Angular 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();
    }

【问题讨论】:

  • 您是否尝试过在一种方法中调用 setItem() 和 get(),确保 localStorage 有效吗?也许这两个组件获得的服务实例不同。
  • 这行得通,现在我如何在整个应用程序中访问相同的存储空间,例如我的 HomeComponent?
  • app.module.ts 中,您注册了NgxLocalStorageModule 提供程序。这应该使服务成为单例。将localStorage构造函数参数保存在组件的成员变量中,并使用this.localStorage访问。
  • @zgue 只是需要更多信息,请更详细一点,哪个构造函数? HomeComponent 构造函数?
  • 使localStorage 也成为AppLoginComponent 的成员,并使用this.localStorage 访问它。这样它必须是注入的服务。

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


【解决方案1】:

我创建了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);
                    });
                });

你不能在构造函数之外使用这样的服务,也不能使用你需要添加'this'的self。并在你的构造函数前缀 localStorage 与 private 并在 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';

尝试在没有 dist 的情况下使用 import

import { FacebookModule } from 'ngx-facebook';

【讨论】:

  • 好的,我已经在 Plunker 中运行了它并查看了代码,但我真的不明白它是如何回答我的问题的。
  • 您想将用户名存储在 LocalStorage 中然后检索它并显示在模板中不是吗??
  • 是的,但是您的 Plunker 示例没有在任何地方显示用户名。
  • 它显示在控制台日志中忘记显示在 UI 中。用户作品是名称。按登录,你会看到。
【解决方案2】:

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

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

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

问候

【讨论】:

  • 对不起,我已经知道了。这不是我遇到的问题。
【解决方案3】:

您应该使用 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
}

【讨论】:

    【解决方案4】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多