Angular is throwing an error that Localstorage is not defined

I'm currently working on a project and have encountered an issue with utilizing localStorage. My goal is to save the count state when the add button is clicked, so that even if I refresh the page, the number will remain intact.

--- cart.service.ts---
key= "count"

private Count = new BehaviorSubject<number>(this.getlocal());
Count$ = this.Count.asObservable();

incrementCount(){
   const newCont = this.Count.value+1;
   this.Count.next(newCont);
   this.setlocal(newCont);
 }

getlocal(): number {
  const storedValue = localStorage.getItem(this.key); 
  return storedValue !== null ? parseInt(storedValue, 10) : 0;
}

setlocal(count: number) {
  localStorage.setItem(this.key, count.toString());
}

Additionally, I have created an app component with the incrementcount function, along with a navcomponent that receives the count via HTML. However, I am encountering error ng0100. Any assistance in resolving this would be greatly appreciated!

Answer №1

When utilizing server-side rendering (SSR) and needing to access browser APIs, it is essential to enclose the code within an afterRender or afterNextRender block. Failure to do so may result in the code being executed on the server side (Node.JS), where functionalities like localStorage are not available. It is also crucial to adjust logic when fetching a value directly from local storage within a function.

private initialCount = new BehaviorSubject<number>(0);

constructor(private readonly environmentInjector: EnvironmentInjector) {
  afterNextRender(() => {
    const storedValue = localStorage.getItem(this.key);
    const count = storedValue !== null ? parseInt(storedValue, 10) : 0;
    this.initialCount.next(count);
  });
}

setLocalStorageCount(count: number) {
  runInInjectionContext(this.environmentInjector, () =>
    afterNextRender(() => localStorage.setItem(this.key, count.toString()))
  );
}

Answer №2

To update the code in cart.service.ts, you can follow these instructions:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CartService {
  private readonly cartKey = 'cartCount';

  // Set initial count to 0 for each new session
  private cartCount = new BehaviorSubject<number>(0);
  cartCount$ = this.cartCount.asObservable();

  constructor() {
    // Reset localStorage count to 0 upon service initialization
    this.setLocalStorage(0);
  }

  incrementCartCount() {
    const newCartCount = this.cartCount.value + 1;
    this.cartCount.next(newCartCount);
    this.setLocalStorage(newCartCount);
  }


  private setLocalStorage(count: number) {
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem(this.cartKey, count.toString());
    }
  }
}

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

Using the up and down arrow keys on the keyboard to navigate through a mat-form-field-infix field in

Is there a way to simulate keyboard inputs for the up and down buttons in a drop-down list while working with mat-form-field-infix? I attempted using Robot framework, but it seems that the drop-down list does not appear unless I manually interact with it ...

useEffect does not trigger a rerender on the primary parent component

I am facing an issue where the main parent component does not re-render when I change the state 'click button' in another component while using useEffect. Oddly enough, the main <App /> component only re-renders properly when I reload the p ...

Transform your TypeScript code with a jscodeshift codemod that removes generic type declarations while preserving the wrapped

I am currently working on developing a codemod that will eliminate all instances of the $ReadOnly<T> generic from a TypeScript codebase, while retaining only T (where T represents an object or union). This is what I have managed to come up with so f ...

A guide on incorporating typings for d3-tip in TypeScript 2.0

Seeking to implement tooltips in my charts using the d3-tip library. After installing typings for d3-tip in Typescript 2.0: npm install @types/d3-tip --save The typings appear in my package.json: "dependencies": { "@types/d3": "^4.7.0", "@types/d3- ...

How to identify a click on a link within the current page using Angular

Is there a way to utilize built-in Angular router properties like RouterLinkActive to detect when a link to the current page is clicked? I am looking to implement a function in the footer that will scroll to the top of the page if the current page link is ...

Downloading Files in Angular Using HttpClient - Extracting File Names from the Server Response

I am currently working on retrieving a File from an API URL. My goal is to display this uploaded file in an input field along with its name. To achieve this, I have implemented the following service function: getDocument(): Observable<Blob> { c ...

Tips for concealing material input

In my usual practice, when I need a form field to be part of the submission but not visible, I typically use <input type="hidden" /> However, when working with matInput, the option for a type of hidden is not available. While I could apply display: ...

Clarity 3 enhancement: Encounter of NullInjectorError with TreeFocusManagerService

Upon updating my project to Angular9/Clarity3 from Angular8/Clarity2, I encountered some issues while navigating the app. I was able to fix some problems, but now I'm facing a NullInjectorError: ERROR Error: Uncaught (in promise): NullInjectorErr ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

What is the best way to reverse the numbers and incorporate borders into the circle using SVG in my particular situation?

I created a circular layout resembling a clock. You can view the code on this link. The following snippet is part of the code from the plnkr: getTransformMatrix() { let t; const res = []; const x = this.items.length - 2; for (let i = 0; i < thi ...

Unit testing the afterClosed() function of Angular Material Dialog with mocking

When I trigger my mat-dialog, I use the following function: accept() { let dialogRef = this.dialog.open(AcceptDialogComponent, { data: { hasAccepted: false } }) dialogRef.afterClosed().subscribe(result => { console.log(result); ...

Ways to refresh the information displayed on the view when the observable data is updated

I am using an observable called getContentfulEntry to retrieve data, while also passing data from another observable known as stateService. this.langSubscription = this.stateService.getLanguage() .subscribe(val => { this.lang = val; ...

Merging arrays with the power of ES6 spread operator in Typescript

My goal is to merge two arrays into one using the spread object method as shown in the code snippet below: const queryVariable = { ...this.state, filters: [...Object.keys(extraFilters || {}), ...this.state.filters], } The this.state.filte ...

Guide on incorporating the handsontable library with Angular 2

As I delve into the realm of configuration in npm, I am attempting to integrate the handsontable library into an Angular 2 project built with angular-cli (ng init). I have included the TypeScript definition for the library as well. Below is the content of ...

Error message when running 'npm serve'

Encountering an issue with running the command: npm run serve To address it, I find that logging out or rebooting my Ubuntu 16.04 is necessary. I've verified that no tasks related to node are currently running. Even after uninstalling and reinstall ...

RC6 - What is the significance of encountering an 'Unexpected token <' error message?

After updating to RC.6, I am encountering a series of errors related to third-party components. Specifically, the error message displayed is: SyntaxError: Unexpected token <. This issue has arisen with ng2-bootstrap, ng2-select, and angular2-jwt. Howev ...

Display an error message in the input type file Form Control if the file format is not .doc or .docx

I need a way to display an alert if the user tries to submit a file that is not of type doc or docx. I've implemented a validator for this purpose and would like the alert message (Unacceptable file type) to be shown when the validation fails. Here i ...

What is the technique for accessing the original function within a class using a proxy?

I attempted to monkey patch a function within my class using Proxy. Is there a way to access and execute the original function? class foo { x = 10; bar() { console.log({ x: this.x }); } } foo.prototype.bar = new Proxy(foo.prototype.bar, { ap ...

Facing difficulties in Angular 8 while trying to import firestore and firebase for an authentication system

While attempting to implement Firestore/Firebase functionalities for Google OAuth signin, I encountered an error indicating that Firebase is not imported: https://i.sstatic.net/oL4rY.png CODE: ERROR in node_modules/@angular/fire/auth/auth.d.ts:4:28 - er ...

Ways to inform TSC that script files won't have shared scope and should disregard redeclarations

Issue to Resolve I am utilizing the TypeScript-powered JavaScript checking capabilities of VSCode to perform type-checking on multiple JS files. These files are intended to be imported via <script> tags in HTML and do not contain any export/import s ...