FacundoGFlores
FacundoGFlores

Reputation: 8128

Defining localstorage for angular2 app

I am using localStorage in an authentication service in one app. Now I am migrating the old app to a new project structure with webpack. Of course, I have different package.json files, but I do not know which specific node module I need.

This is the error:

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

The component for login is entirely copied to the new project, and it has not any compilation errors, I added the component and authentication service to my app.module but I get that error.

How do I set up package.json and app.module.ts files for defining localStorage?

These are the files:

app.module.ts

import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
// import { DataTableModule, SharedModule} from 'primeng/primeng';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { LoginComponent } from './components/login/login.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';

import { AuthenticationService } from './components/login/authentication.service';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        LoginComponent
    ],
    providers: [
        AuthenticationService
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'login', component: LoginComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: '**', redirectTo: 'home' },
        ])
    ]
})
export class AppModule {
}

package.json

{
  "name": "Angular2Spa",
  "version": "0.0.0",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@angular/router": "3.0.0",
    "@types/node": "^6.0.38",
    "angular2-platform-node": "~2.0.10",
    "angular2-universal": "~2.0.10",
    "angular2-universal-polyfills": "~2.0.10",
    "aspnet-prerendering": "^1.0.6",
    "aspnet-webpack": "^1.0.11",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "es6-shim": "^0.35.1",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "5.0.0-beta.12",
    "style-loader": "^0.13.0",
    "to-string-loader": "^1.1.5",
    "ts-loader": "^0.8.2",
    "typescript": "^2.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^1.12.14",
    "webpack-externals-plugin": "^1.0.0",
    "webpack-hot-middleware": "^2.10.0",
    "webpack-merge": "^0.14.1",
    "zone.js": "^0.6.21"
  }
}

This is the code where the error is produced:

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

}

Upvotes: 1

Views: 2540

Answers (1)

dokkis
dokkis

Reputation: 366

localStorage should be defined at global JS level, but you don't have the Typescript definition for it so the compiler says that is not defined.

Just try to put at the start of the file

declare var localStorage : any;

and then use localStorage in the TypeScript code.

You can also try to use angular2-localstorage module.

Upvotes: 1

Related Questions