最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Undefined on localStorage.getItem in Angular - Stack Overflow

programmeradmin1浏览0评论

I'm working on a project with multiple ponents that need to share data saved in local storage. I manage to save them as an object with setItem but when I'm trying to get them I get "undefined" in console.log.

Function for saving on (click):

  saving() {
    let dataStorage = {
      departureDate: this.departureDate,
      returnDate: this.returnDate,
      departureAirport: this.departureAirport,
      arrivalAirport: this.destinationAirport,
      passengersNumber: this.numberOfPassengers
    };
    localStorage.setItem("flightdetails", JSON.stringify(dataStorage));
    this.showStorage = JSON.parse(localStorage.getItem("flightdetails"));
  }

  testLocal() {
    console.log(this.showStorage); //Here I get undefined
  }

All variables are declared:

public numberOfPassengers: number = 1;
  public departureDate: any;
  public returnDate: any;
  public departureAirport: string;
  public destinationAirport: string;
  public showStorage: any;

Also I'm not sure how to call local storage element in another ponent to display. Currently I have ponent called summary:

COMPONENT.TS:

export class SummaryComponent implements OnInit {
  public showStorage = "";
  constructor() {
    this.showStorage = localStorage.getItem("flightDetails");
  }

HTML for summary:

Departure date: {{ showStorage.departureDate}}   

STACKBLITZ:

Thanks for your support in solving this!

I'm working on a project with multiple ponents that need to share data saved in local storage. I manage to save them as an object with setItem but when I'm trying to get them I get "undefined" in console.log.

Function for saving on (click):

  saving() {
    let dataStorage = {
      departureDate: this.departureDate,
      returnDate: this.returnDate,
      departureAirport: this.departureAirport,
      arrivalAirport: this.destinationAirport,
      passengersNumber: this.numberOfPassengers
    };
    localStorage.setItem("flightdetails", JSON.stringify(dataStorage));
    this.showStorage = JSON.parse(localStorage.getItem("flightdetails"));
  }

  testLocal() {
    console.log(this.showStorage); //Here I get undefined
  }

All variables are declared:

public numberOfPassengers: number = 1;
  public departureDate: any;
  public returnDate: any;
  public departureAirport: string;
  public destinationAirport: string;
  public showStorage: any;

Also I'm not sure how to call local storage element in another ponent to display. Currently I have ponent called summary:

COMPONENT.TS:

export class SummaryComponent implements OnInit {
  public showStorage = "";
  constructor() {
    this.showStorage = localStorage.getItem("flightDetails");
  }

HTML for summary:

Departure date: {{ showStorage.departureDate}}   

STACKBLITZ: https://stackblitz./edit/flight-date-pikcer

Thanks for your support in solving this!

Share Improve this question asked Jun 16, 2020 at 7:34 JoseTurronJoseTurron 2432 gold badges6 silver badges22 bronze badges 1
  • localStorage isn't meant to facilitate data sharing between ponents. For that look into singleton services. In your case, if you call testLocal() function before saving() is plete, then the variable showStorage isn't assigned any value yet. And in the other ponent, you would do the same JSON.parse(localStorage.getItem("flightDetails")). But it is usually good practice to check if the data obtained from local storage is null before trying to use it. It means the data isn't available. – Barremian Commented Jun 16, 2020 at 7:40
Add a ment  | 

2 Answers 2

Reset to default 2

It's because the showStorage field is redeclared on each ponent init. So after clicking To summary button which redirects to another view, the showStorage field is destroyed as well as the whole ponent. After going back to the FlightComponent, it's initialized again and that's why the showStorage is undefined. To make it work as you expect, you can assign it a value when creating FlightComponent:

constructor(private router: Router) {
  this.showStorage = localStorage.getItem("flightdetails") || {};
}

That way the variable will hold the value of your localStorage item or an empty object if the value has not been set yet.

Well, I do get value when I try this on my console. https://jsfiddle/wickedrahul/mp68hd09/2/

Chances are you might need to call saving() inside testLocal() so the value of this.showStorage could be assigned.

  function saving() {
    let dataStorage = {
      departureDate: "foo",
      returnDate: "foo",
      departureAirport: "foo",
      arrivalAirport: "foo",
      passengersNumber: "foo"
    };
    localStorage.setItem("flightdetails", JSON.stringify(dataStorage));
    return JSON.parse(localStorage.getItem("flightdetails"));
  }

  function testLocal() {
    return saving();
  }

   var a = testLocal()
   console.log(a);
发布评论

评论列表(0)

  1. 暂无评论