Why does my Array disappear when I refresh the page, even though I have LocalStorage set up?

When I invoke the add method in my template, it is supposed to allow me to add new objects into the eintraege-array. According to sources online, this data should be stored using LocalStorage so that when I refresh the page, all my changes are saved. However, this doesn't seem to be happening. Below is the add method called in a component, which then triggers another saveData method from one of the LocalStorage-Methods.

eintraege: Eintrag[] = [];
  
  add(beschreibung: string, faelligkeitsdatum: string) {

      var eintrag: Eintrag = {
        beschreibung: '',
        faelligkeitsdatum: '',
        erledigt: false,
      };

      eintrag.beschreibung = beschreibung;
      eintrag.faelligkeitsdatum = faelligkeitsdatum;
      eintrag.erledigt = false;

      this.eintraege.unshift(eintrag);

      this.eintragService.saveData('token', JSON.stringify(this.eintraege))

Here is an example of my service using LocalStorage:

public saveData(key: string, value: string) {
    localStorage.setItem('token', value);
  }

EDIT: I also use the getItem Method:

ngOnInit(): void {
    this.getEintraege();
  }
getEintraege(): void {
    this.eintragService.getData('token')
  }

In my service, the getData method is implemented as follows:

 public getData(key: string) {
    return localStorage.getItem(key)
  }

Despite these steps, upon refreshing the page, all data seems to disappear.

Answer №1

you should include this code snippet in your component

ngAfterViewInit() {
    this.userData = localStorage.getItem('authToken')
}

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

Issue when making a call to a web service using TypeScript

I've implemented the following TypeScript code: /// <reference path="jquery.d.ts" /> interface INotificationService { serviceUrl: string; getNotifications(onNotificationReceived: (notifications: string) => any): void; } module GRCcon ...

Using JSON data to populate models in Angular

I am currently working on a project where I have defined a model in my class as follows: model = new questions( 1, // Id '', // Name &ap ...

Conceal digits in PIN input field - IONIC version 5

I am working on an app that requires users to enter a PIN. Here is the HTML code for the input fields: <div class="contain-pin"> <ion-row> <ion-col size="2"></ion-col> <ion-col size="2&qu ...

Encountering the error message "The argument type 'AsyncThunkAction<*>' cannot be assigned to the parameter type 'Action<any>'" while trying to utilize a custom typed useAppDispatch hook

For a live example, you can check out this link. In the process of developing a React application with TypeScript and Redux Toolkit, I have meticulously followed the guidelines outlined in the documentation. As a result, I have successfully implemented ty ...

Tips for accessing the PR number in a Node.js GitHub Probot listening for the `pull_request` event

I've recently developed a GitHub probot application using nodejs and typescript. Currently, I have set up an event listener for the pull_request event. How can I extract the pr_number from the context object within the probot? The snippet below is fr ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...

Incorporating an Angular Application into an Established MVC Project

I am working on an MVC project within an Area of a larger solution. My goal is to incorporate an Angular App into this area and integrate it with my MVC project. The catch is that this is not a .Net Core Mvc project. How can I configure my project to utili ...

No output returned by SwitchMap in Angular 2

I'm facing an issue with my SwitchMap implementation and struggling to resolve it. The problem occurs when I have a collection of category buttons that, when clicked, trigger a server call to load the corresponding data. However, if I switch between t ...

Waiting for an Angular Observable to complete its process

I have recently developed a small Angular application that retrieves data from a REST API using observables. However, I am facing an issue with their asynchronous nature. let tempArray: boolean[] = []; for (let i = 0; i < 3; i++) { this._myservice. ...

Create a function with an optional argument when the type can be inferred as an empty object

Is there a way to enforce a function's argument to be required if it has keys in the inferred type, and optional if it does not exist or is an empty object? I've experimented with conditionals and overloads but have yet to find a solution. const ...

Is it feasible to determine the precise class of an object while utilizing a variable that possesses a union type in Typescript?

Currently delving into Typescript and running tests. Upon using console.log, I received an object. Given its typed nature, I anticipated it to accurately determine the type of variable c. interface Car { gears: number } interface Bike{ gears: number ...

Creating Class Names Dynamically in Angular 2 Using ngFor Index

Encountering an issue while trying to generate a dynamic class name based on the ngFor loop index in Angular 2. Due to restrictions, I had to use a specific syntax as Angular 2 does not support ngFor and ngIf together on the same element. Given this setup ...

I'm having trouble with npm install, it's not working as expected

After downloading node.js, I encountered errors when trying to run the CLI command npm install -g @angular/cli: npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to http://registry.npmjs.org/@angular%2fcli failed, reason: getaddrin ...

Switch statements in TypeScript may not function properly with type guards when assigning an object to a variable

I'm puzzled as to why the type guard is not working in the example provided below... Considering the following interfaces: interface ParamA { name: 'A'; aaa: boolean; } interface ParamB { name: 'B'; bbb: number; ...

Strategies for effectively passing parameters to animation step functions

By breaking down an animation function into reusable parts, I created the following structure: const enterLeaveAnimation = ( triggerName: string, step1: AnimationMetadata | AnimationMetadata[], step2: AnimationMetadata | AnimationMetadata[] ) => t ...

Potential absence of object in strict mode

I have encountered the error message Object is possibly null in typescript specifically for the event handler below, while other event handlers I've written do not trigger this error: <input type="file" className="hide" ...

Refreshing the page resolves unhandled errors that occur when an item is removed from local storage

I'm currently working on adding a logout button to my website. I have the user's token saved in local storage, but when the logout button is clicked and the token is removed from local storage, an error occurs upon redirecting back to the login p ...

Using Regular Expressions to Validate Emails: Ensuring Only One "@" Sign Appears

In my Angular 2 application, I have been using the following regular expression to validate email addresses: ^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)$ Although the validation is successful for most cases, it fails when th ...

Troubleshooting Issues with Imports after Integrating Typescript into Vue and Rails Application

I attempted to integrate TypeScript into my existing VueJS + Rails application. I started by cloning a demo from (https://github.com/gbarillot/rails-vue-demo-app) and then following the guidelines provided on https://github.com/rails/webpacker $ bundle ex ...

Can you explain the contrast between the @HostBinding() directive and ElementRef/Renderer in Angular?

I'm currently in the process of developing a directive for a dropdown toggle feature. Through my research, I have come across two different approaches to implement this directive. Which method would be considered the most effective practice? Approach ...