2017-09-06 3 views
2

Ich versuche, Benutzerauthentifizierung mit Angular und ASP.NET Core zu machen.ReferenceError: localStorage ist nicht definiert

Ich bin nach dem Tutorial hier:

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

ich alle Schritte ohne Fehler gefolgt.

Die App läuft, aber wenn ich auf "/ Register" oder "/ login" Routen, bekomme ich

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

der Dienst, der es verwendet wird:

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

das Register ts ist:

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

das Login ist:

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

habe ich versucht, die Lösung aus:

localStorage is not defined (Angular Universal)

aber es funktioniert nicht ...

Was ich

+0

Hallo, haben Sie es geschafft, Fehler zu beheben? Ich bin mit dem gleichen Problem konfrontiert ... –

+0

Ich beendete mit einer Bibliothek. angular2-cool-storage funktioniert wirklich gut –

Antwort

2

Sie Standard-API für localstorage, wie

localStorage.setItem(k, v) 

und

localStorage.getItem(k) 

aber Wenn Sie ein möchten verwenden bekommen Winkel Lösung für diese und eine gute Bibliothek für local zu finden, ein Ich verwende das ist

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

auch

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

cool zu verwenden.

+0

ja, aber warum bekomme ich diesen Fehler? Ps.s. Mein Projekt finden Sie hier https://github.com/dobrinsky/AngularDefault –

3

Der Standard localStorage API verfügbar bin fehlen sollte.

Keine Notwendigkeit, es zu deklarieren.

setzen localStorage.setItem('name', 'storingSomething');

localStorage.getItem('name');

+0

ja, aber warum bekomme ich diesen Fehler? Ps.s. Mein Projekt kann hier gefunden werden https://github.com/dobrinsky/AngularDefault.git –

+0

Sind Sie überprüft durch Entfernen von 'declare var localStorage: any;' immer noch vor demselben Problem? – k11k2

+0

Ja, ich habe das versucht und kein Glück. Ich versuchte @Rakeschands Antwort mit CoolStorage und es funktionierte ... –

Verwandte Themen