Utilizing localStorage in an authentication service within my app, I am currently in the process of transitioning the old app to a new project structure with webpack. While each app has its own unique package.json
file, I am unsure about the specific node module required.
The error message reads as follows:
Exception: Call to Node module failed with error: Error: Uncaught (in promise): ReferenceError: localStorage is not defined
The login component has been successfully copied over to the new project without any compilation errors. After adding both the component and authentication service to my app.module
, however, I continue to encounter this error.
What steps should I take to configure the package.json
and app.module.ts
files for defining localStorage
?
The relevant files are outlined below:
app.module.ts
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
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,
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": {
// List of dependencies
}
}
The area where the error occurs is highlighted below:
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) {
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(username, password): Observable<boolean> {
//...
}
logout(): void {
this.token = null;
localStorage.removeItem('currentUser');
}
}