Creating storage solutions for an Angular 2 application

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

}

Answer №1

Global JavaScript level should have the localStorage defined, lack of TypeScript definition causing compiler errors.

To resolve this issue, begin the file with:

declare var localStorage : any;

Then utilize localStorage in your TypeScript code.

An alternative solution is to consider using the angular2-localstorage module.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - issue with getting window.screen.height in template

One issue I'm facing is when attempting to optimize a section of my template for mobile devices in landscape mode. TS: window = window; Template: <div [ngStyle]="{'height': window.innerHeight < window.innerWidth ? window.screen ...

Typescript library available as a private npm dependency

I have developed a Typescript library that I bundle as an npm module. During the development of my frontend application, I easily integrated this library using yarn link. As I set up GitLab CI for other developers to work on the frontend application, I am ...

When using setInterval, the image remains static on Safari but updates on Chrome

In my project, I am using a mock array to distribute data. One part of the project utilizes this data to display a list of cases, each with assigned images. When a case is hovered over, the images associated with that case are displayed one at a time, with ...

What is the trick to make the "@" alias function in a Typescript ESM project?

My current challenge involves running a script using ESM: ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts Despite my efforts, the script seems unable to handle imports like import '@/server/init.ts': CustomError: Cannot ...

Troubleshooting Ng Serve Module Conflict

My latest project involved creating a chatbot system. However, whenever I try to open the system, an error pops up on the command prompt. I attempted to troubleshoot by uninstalling and reinstalling npm, but the issue persists. Below is a link to an image ...

Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? ...

The art of connecting with Angular 2 router and Components

Here are the elements I have: <app-scrollable-area (scrolledDown)="..." class="scrollable-y"> <router-outlet></router-outlet> </app-scrollable-area> I'm wondering how to communicate this event (scrolledDown) to inside ...

What is the proper way to create a React Context in TypeScript that accepts both a ref and a setState function as arguments?

When encountering various errors, one of them being: Type 'Dispatch<SetStateAction<null>>' is not assignable to type '() => void' My code looks something like this: import React, { ReactElement, ReactNode, useEffec ...

I have tried to install Angular Animations but have encountered difficulty importing it into my project

I attempted to incorporate Animations into my project. C:\gtaui>npm install @angular/animations --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04637065716d44342a342a34">[email protected]</a> C:&bso ...

Facing issues with building Angular 7 and Ionic 4 - getting error message "TypeError: Cannot read properties of undefined (reading 'kind')"

I need assistance with a problem I am encountering while building my Angular 7 & Ionic 4 application... When I run the ng build --prod command, I encounter the following error: ERROR in ./node_modules/ionic4-auto-complete/fesm5/ionic4-auto-complete.js ...

calling an Angular template function

Can the convert function be called in an Angular template like covert{{item.size}}? If so, what is the correct syntax to use? Thank you. <mat-cell *matCellDef="let item" fxHide fxShow.gt-xs fxShow.gt-md [matTooltip]="item.size"> ...

Issues arise when utilizing res.cookie, however, there are no troubles when using res.json

Using res.json() in my Express POST route response works fine. However, when I switch to using res.cookie(), I run into a strange issue of receiving a MongoDB 11000 Dup Key Error. The behavior that follows is somewhat puzzling: The Document is successfull ...

Styling the `mat-hint` in Angular Material for large blocks of text

Currently, I am undertaking a project in Angular 9 and utilizing Material design. If you want to view a demo of my work, you can find it here: https://stackblitz.com/edit/mat-hint-styling-issue?file=src/app/app.component.html In my project, I am using in ...

Exploring the depths: How to navigate through a complex nested object in an Angular 6 template

I have retrieved an object from a service structured as shown below let obj = [ 0: { key1: 'val', key2: 'val', key3: [{ key1: 'val', key2: 'val', key3: []; }] ...

Error: Unable to access the 'TigerNo' property of an undefined object. Setting tempObj['TigerNo'] to the default TigerNo value from the sports record

I need some help with JavaScript programming. Although I am able to retrieve values in sportsRecord, I am encountering difficulties assigning them to tempObj['TigerNo']. Whenever I try to assign the value, I encounter the following error message ...

Adding zIndex in typescript and MUI: A step-by-step guide

**Hello, I am facing an issue with my CSS on Vercel. It works fine locally but some styles are not being applied once the project is on Vercel. I was able to fix the background color issue by using !important. However, I am now struggling with applying the ...

Maximize efficiency by running ng serve on multiple machines at the same time with Angular

Currently, I require the ability to run my Angular application on multiple machines simultaneously. While I can grant access to other machines using ng serve --public-host 192.168.1.1, I also need to be able to run the same app on my own machine. Do you k ...

Deciding Between Utilizing Observables or Promises in Angular

Having delved into Observables after transitioning from a predominantly Promise-based application, I recognize their effectiveness in handling streams and event patterns. However, I can't help but feel that there are instances where using Observables ...

Enhancement of Nebular Theme from version 4.4.0 to 9.0.1 in relation to Angular (from 8.2.3 to 13.2.1)

Upon upgrading from Nebular Theme version 4.4.0 to 9.0.1 and Angular version 8.2.3 to 13.2.1, I encountered the following issues: 'nb-card-header' is not recognized as a valid element: If 'nb-card-header' is an Angular component, ens ...

Half the time, the Paypal button fails to load on Angular

My page has a recurring issue with a PayPal button that fails to load half the time. I recently experienced this problem when refreshing the page 30 times in a row – it alternated working properly for 9 times, then failed to load for 11 consecutive times ...