Trying to add a service which uses localstorage fail #1319

Closed
opened 2025-08-09 17:19:41 +00:00 by fergalmoran · 0 comments
Owner

Originally created by @FacundoGFlores on 10/13/2016

I am trying to add the following service:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService {
    public token: string;
    public codusuario: string;
    constructor(private http: Http) {
        // set token if saved in local storage
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
    }

    login(username, password): Observable<boolean> {
        //...
    }

    logout(): void {
        // clear token remove user from local storage to log user out
        this.token = null;
        localStorage.removeItem('currentUser');
    }
}

I added it to the app.module.ts. But it gives me the following error:

Exception: Call to Node module failed with error: Error: Uncaught (in promise): ReferenceError: localStorage is not defined

I am trying to migrate this service from a yeoman project structure: https://www.npmjs.com/package/generator-aspnetcore-angular2, where the service works fine.

Why it is not working here?

*Originally created by @FacundoGFlores on 10/13/2016* I am trying to add the following service: ``` import { Injectable } from '@angular/core'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' @Injectable() export class AuthenticationService { public token: string; public codusuario: string; constructor(private http: Http) { // set token if saved in local storage var currentUser = JSON.parse(localStorage.getItem('currentUser')); this.token = currentUser && currentUser.token; } login(username, password): Observable<boolean> { //... } logout(): void { // clear token remove user from local storage to log user out this.token = null; localStorage.removeItem('currentUser'); } } ``` I added it to the `app.module.ts`. But it gives me the following error: > Exception: Call to Node module failed with error: Error: Uncaught (in promise): ReferenceError: localStorage is not defined I am trying to migrate this service from a yeoman project structure: https://www.npmjs.com/package/generator-aspnetcore-angular2, where the service works fine. Why it is not working here?
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github/JavaScriptServices#1319
No description provided.