【问题标题】:ReferenceError: localStorage is not definedReferenceError: localStorage 未定义
【发布时间】:2018-02-14 18:33:19
【问题描述】:

我正在尝试使用 Angular 和 ASP.NET Core 进行用户身份验证。

我正在关注此处的教程:

https://fullstackmark.com/post/10/user-authentication-with-angular-and-asp-net-core

我按照所有步骤都没有错误。

应用程序运行,但是当我转到“/register”或“/login”路由时,我得到了

NodeInvocationException: Uncaught (in promise): ReferenceError: localStorage is not defined
ReferenceError: localStorage is not defined

使用它的服务是:

import { Injectable, Inject } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { UserRegistration } from '../shared/models/user.registration.interface';
import { ConfigService } from '../shared/utils/config.service';

import { BaseService } from "./base.service";

import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';

//import * as _ from 'lodash';

// Add the RxJS Observable operators we need in this app.
import '../rxjs-operators';

@Injectable()
export class UserService extends BaseService {

  baseUrl: string = '';

  // Observable navItem source
  private _authNavStatusSource = new BehaviorSubject<boolean>(false);
  // Observable navItem stream
  authNavStatus$ = this._authNavStatusSource.asObservable();

  private loggedIn = false;

  constructor(private http: Http, private configService: ConfigService) {
    super();
    this.loggedIn = !!localStorage.getItem('auth_token');
    // ?? not sure if this the best way to broadcast the status but seems to resolve issue on page refresh where auth status is lost in
    // header component resulting in authed user nav links disappearing despite the fact user is still logged in
    this._authNavStatusSource.next(this.loggedIn);
    this.baseUrl = configService.getApiURI();
  }

    register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
    let body = JSON.stringify({ email, password, firstName, lastName,location });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.baseUrl + "/accounts", body, options)
      .map(res => true)
      .catch(this.handleError);
  }  

   login(userName: any, password: any) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
      this.baseUrl + '/login',
      JSON.stringify({ userName, password }),{ headers }
      )
      .map(res => res.json())
      .map(res => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      })
      .catch(this.handleError);
  }

  logout() {
    localStorage.removeItem('auth_token');
    this.loggedIn = false;
    this._authNavStatusSource.next(false);
  }

  isLoggedIn() {
    return this.loggedIn;
  }  
}

寄存器ts是:

import { Component, OnInit, Inject } from '@angular/core';
import { Router } from '@angular/router';

import { UserRegistration } from '../../shared/models/user.registration.interface';
import { UserService } from "../../services/user.service";

declare var localStorage: any;

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html'
})
export class RegistrationFormComponent implements OnInit {

 errors: string;  
 isRequesting: boolean;
 submitted: boolean = false;

 constructor(private userService: UserService, private router: Router) { 

 }

  ngOnInit() {

  }

  registerUser({ value, valid }: { value: UserRegistration, valid: boolean }) {
     this.submitted = true;
     this.isRequesting = true;
     this.errors='';
     if(valid)
     {
         this.userService.register(value.email,value.password,value.firstName,value.lastName,value.location)
                   .finally(() => this.isRequesting = false)
                   .subscribe(
                     result  => {if(result){
                         this.router.navigate(['/login'],{queryParams: {brandNew: true,email:value.email}});                         
                     }},
                     errors =>  this.errors = errors);
     }      
  }  
}

登录是:

import { Subscription } from 'rxjs';
import { Component, OnInit,OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { Credentials } from '../../shared/models/credentials.interface';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'app-login-form',
  templateUrl: './login-form.component.html'
})
export class LoginFormComponent implements OnInit, OnDestroy {

  private subscription: Subscription;

  brandNew: boolean;
  errors: string;
  isRequesting: boolean;
  submitted: boolean = false;
  credentials: Credentials = { email: '', password: '' };

  constructor(private userService: UserService, private router: Router,private activatedRoute: ActivatedRoute) { }

    ngOnInit() {

    // subscribe to router event
    this.subscription = this.activatedRoute.queryParams.subscribe(
      (param: any) => {
         this.brandNew = param['brandNew'];   
         this.credentials.email = param['email'];         
      });      
  }

   ngOnDestroy() {
    // prevent memory leak by unsubscribing
    this.subscription.unsubscribe();
  }

  login({ value, valid }: { value: Credentials, valid: boolean }) {
    this.submitted = true;
    this.isRequesting = true;
    this.errors='';
    if (valid) {
      this.userService.login(value.email, value.password)
        .finally(() => this.isRequesting = false)
        .subscribe(
        result => {         
          if (result) {
             this.router.navigate(['/home']);             
          }
        },
        error => this.errors = error);
    }
  }
}

我尝试了以下解决方案:

localStorage is not defined (Angular Universal)

但它不起作用......

我错过了什么

【问题讨论】:

  • 您好,您解决错误了吗?我面临同样的问题...
  • 我结束了使用库。 angular2-cool-storage 真的很棒

标签: angular


【解决方案1】:

您可以使用标准 API 进行本地存储,例如

localStorage.setItem(key, val)

localStorage.getItem(key)

但是如果你想要一个角度解决方案并找到一个好的本地存储库,我正在使用的是这个

https://github.com/marcj/angular2-localstorage

还有

https://www.npmjs.com/package/angular2-cool-storage

使用起来很酷。

【讨论】:

  • 是的,但为什么会出现此错误?附:我的项目可以在这里找到github.com/dobrinsky/AngularDefault
  • angular2-localstorage 表示不再维护。
  • @java-addict301 你可以使用js的标准服务localstorage或者还有其他好的库,如ngx-webstorage-serviceangular-webstorage-service,如果你了解如何使用本机服务比不需要为它使用外部库。干杯,希望我有所帮助
【解决方案2】:

标准localStorage API 应该可用。

无需声明。

设置 localStorage.setItem('name', 'storingSomething');

得到 localStorage.getItem('name');

【讨论】:

  • 是的,但为什么会出现此错误?附:我的项目可以在这里找到github.com/dobrinsky/AngularDefault.git
  • 您是否通过删除 declare var localStorage: any; 进行了检查,您仍然面临同样的问题吗?
  • 是的,我试过了,但没有运气。我用 CoolStorage 尝试了@Rakeschand 的答案,它奏效了......
  • @AndreiDobrin 很好,您为什么不尝试我上面提到的“POC”示例,以便我们了解真正的问题。
  • 我试过了,但它不起作用...我不断收到错误
【解决方案3】:

您可能会收到此错误,因为组件在渲染服务器端时正在寻找 localStorage,这就是为什么找不到它并且您收到此错误消息的原因。

我在 React 中遇到了类似的问题,并通过简单地动态导入组件、禁用 SSR 来解决它。即使只是禁用 SSR 也应该没问题,您可以选择是在导入还是导出时执行此操作。

希望这能解决你的问题

【讨论】:

    【解决方案4】:

    localStorage.getItem(...) 放在`ComponentDidMount()`上

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 2012-08-24
      • 2021-09-12
      • 1970-01-01
      • 2015-10-04
      • 2017-04-10
      相关资源
      最近更新 更多