Q:

Undefined on localStorage.getItem in Angular

I'm working on a project with multiple components 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 component to display. Currently I have component 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.com/edit/flight-date-pikcer
Thanks for your support in solving this! 

A:

It's because the showStorage field is redeclared on each component init. So after clicking To summary button which redirects to another view, the showStorage field is destroyed as well as the whole component. 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.

