The function threw an error: "TypeError: this.registeredUserArray.some is not a function"

I have been attempting to store a registered user object inside localstorage. However, when I try to retrieve or set those values from localstorage in an array and parse it back to an object, I encounter an error stating that ".push" or ".some" is not a function.

import { Injectable } from '@angular/core';
import { Cart } from 'src/app/models/cart';
import { Product } from 'src/app/models/product';
import { productAndQuantity } from 'src/app/models/product-and-quantity';
import { User } from 'src/app/models/user';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {

  registeredUserArray : User[];
  tempCart: Cart = new Cart;
  purchaseHistoryCartArray: Cart[] = [];
  localStorageKey = "registeredUserArray";


  defaultUsers : User[] = [
    {
      username : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd8ccccffd8d0d0d8d3da91dcd0d2">[email protected]</a>",
      password : "BruceWayne@123",
      isAdmin : true,
    },
    {
      username : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa8e9f898eba9d979b9396d4999597">[email protected]</a>",
      password : "BruceWayne@123",
      isAdmin : false,
      tempCart: new Cart,
      purchaseHistoryCartArray: []
    },
  ]

  constructor() {

    if (JSON.parse(localStorage.getItem(this.localStorageKey)!))
    {
      this.registeredUserArray = JSON.parse(localStorage.getItem(this.localStorageKey)! ?? []);
    }
    else 
    {
      this.registeredUserArray = this.defaultUsers;
      localStorage.setItem(this.localStorageKey, JSON.stringify(this.defaultUsers));
    }
  }

  addUser(user : User)
  {
    // this.registeredUserArray.push(user); 
    console.log(JSON.parse(localStorage.getItem(this.localStorageKey)!))
    this.registeredUserArray.push(user); **<--this is the point of error**
    localStorage.setItem(this.localStorageKey, JSON.stringify(this.registeredUserArray));
  }

Answer №1

Could you please attempt the following code snippet?

import { Injectable } from '@angular/core';
import { Cart } from 'src/app/models/cart';
import { Product } from 'src/app/models/product';
import { productAndQuantity } from 'src/app/models/product-and-quantity';
import { User } from 'src/app/models/user';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {

  registeredUserArray: User[];
  tempCart: Cart = new Cart();
  purchaseHistoryCartArray: Cart[] = [];
  localStorageKey = "registeredUserArray";

  constructor() {
    const storedData = localStorage.getItem(this.localStorageKey);

    if (storedData) {
      this.registeredUserArray = JSON.parse(storedData);
    } else {
      this.registeredUserArray = this.defaultUsers;
      localStorage.setItem(this.localStorageKey, JSON.stringify(this.defaultUsers));
    }
  }

  addUser(user: User) {
    this.registeredUserArray.push(user);
    localStorage.setItem(this.localStorageKey, JSON.stringify(this.registeredUserArray));
  }

  // ... other methods ...

}

Answer №2

The following code snippet contains a handler:

constructor() {
  this.localStorageHandler(this.localStorageKey,this.defaultUsers);
}

//helper function

public localStorageHandler(key:string, dataToStore) {
 const localStoreData = JSON.parse(localStorage.getItem(key);
  if (localStoreData && Array.isArray(localStoreData))
    {
      this.registeredUserArray = localStoreData;
      return;
    }
    this.registeredUserArray = dataToStore;
    localStorage.setItem(key, JSON.stringify(this.defaultUsers));
}

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

Displaying icons representing different countries using Angular framework

Seeking assistance with Angular - I obtained a collection of country icons (svg format) from flat icon and intend to display them based on the respective countries in my project. With 870 icons, what would be the simplest approach to accomplish this with ...

What exactly is the most efficient method for validating fields within an Angular template?

My reactive form is currently displaying a validation message for each field that is not valid. However, I noticed that I was repeatedly using the check !!(!form.get(field)?.valid && form.get(field)?.touched); in every input field. So, I decided to ...

Importing Angular Circular Module for your project

I have encountered a situation where I have two Modules with components that need to use each other. This means that I have to import "word" in "test" and "test" in "word" which results in an error. How can I resolve this issue? Module "test": @NgModu ...

What is the most effective method for structuring JSON data that is utilized by a single-page application (SPA)?

A colleague and I are collaborating on a single page application (built in React, but the framework used isn't crucial; the same query applies to Angular as well). We have a database with 2 interconnected tables: Feature Car Both tables are linked ...

Angular2 Date Picker Validation: Ensuring Proper Date Selection

I have implemented a custom directive for a date picker in my project. Below is the code snippet of the template: <div class="input-group"> <input type="text" id="tbxDate" pattern="\d{1,2}/\d{1,2}/\d{4}" ...

"Implementing material-ui in Angular 7: A Step-by-Step Guide

I am looking to integrate material-ui into my Angular 7 project. While I know that Angular Material is available, I prefer using ui-material over it. However, I am unsure about how to implement ui-material in an Angular environment. ...

Navigating a Laravel application with Angular 7: A comprehensive guide

Setting up a local server with LAMP, I am incorporating Laravel for the backend and Angular 7 for the frontend. Included in my web.php file is: <?php /* |-------------------------------------------------------------------------- | Web Routes |------ ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

Stop const expressions from being widened by type annotation

Is there a way to maintain a constant literal expression (with const assertion) while still enforcing type checking against a specific type to prevent missing or excess properties? In simpler terms, how can the type annotation be prevented from overriding ...

Traverse the elements of a BehaviorSubject named Layer_Template

I am currently facing an issue with displaying data from my BehaviorSubject. I have come across a way to iterate through a BehaviorSubject using asyncpipe which subscribes to the Observable SERVICE todo.service.ts @Injectable() export class TodoService ...

Is there a solution for resolving the 'cannot post error' in nodejs?

Recently started using node.js I am currently working on a nodejs-experss-mongodb project and I am in the process of implementing a subscription feature that has the following specific requirements: Request Method: POST URL: localhost:8080/api/v1/users/: ...

Encountering tsconfig.json issues following the integration of Tailwindcss v3 into Next.js (create-next-app --typescipt)

Upon opening my code in VS Code, I encountered the following error: Cannot find type definition file for 'accepts'. The file is in the program because: Entry point for implicit type library 'accepts' In an attempt to resolve this issue ...

Managing errors in ErrorHandler and addressing them in HttpInterceptor

Can you explain the difference between error handling methods in Angular 7? Is it necessary to handle global errors in HttpInterceptor and also in Angular's built-in ErrorHandler? In the HttpInterceptor, what types of errors can be handled, and in the ...

In Angular, the process of duplicating an array by value within a foreach function is not

I have been attempting to duplicate an array within another array and make modifications as needed. this.question?.labels.forEach((element) => { element["options"] = [...this.question?.options]; // I've tried json.stringify() as wel ...

Differentiating response.data typing on the front end in Typescript depending on the request's success status

Consider this scenario: A secure API authentication route that I am not allowed to access for viewing or editing the code returns interface AuthSuccess { token: string user: object } on response.data if the email and password provided are correct, but ...

Understanding authorization and user roles within an Angular 2 application utilizing Microsoft Graph

As a newcomer, I am in the process of developing a CVThèque application using angular 2 and .net core. For authentication purposes, I have integrated Microsoft Graph and adal successfully. However, I am unsure how to set up permissions and group roles for ...

Creating unique custom 404 error pages for specific sub-directories within NextJS using the App Router Structure

Having trouble with my custom 404 error page (= not-found.tsx) files. I have two of them, one within app/(paths) and another within app/(paths)/(jobs)/jobs/(cats). The issue is that the first not-found file should render when a user visits url example myap ...

Setting a custom port for your Node.js Typescript project on Heroku

In the usual case, Heroku dynamically assigns a port for us. const PORT : string|number = process.env.PORT || 5000; However, how can I alter this code to handle the PORT... utilizing the => TypeScript shorthand? server.listen(port => { console.l ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

Angular POST sends null to .NET Core API

I've been encountering an issue while trying to send data from Angular to my .NET Core API, as the received data always ends up being null. Take a look at my code: Here is the Angular POST request: public insertCategory(categoryToInsert: ICategoryDTO ...