-2

I'm trying to get data from a URL that gives JSON output to an Angular project.

When I follow http://localhost:3000/booking on the browser it gives following output

[{"_id":"5cf35bbebaa52f4ab2f27b81","firstname":"lahiru","lastname":"madushan","email":"lahiru@lahiru.com","contact":770095174,"comments":"Done","xl":2,"md":1,"sm":3,"store":null,"pickup":null,"store_id":"df4xrttfvy","__v":0},
 {"_id":"5cf3762e7410e55137b65c4e","firstname":"lahiru","lastname":"madushan","email":"lahiru@lahiru.com","contact":770095174,"comments":"Done","xl":2,"md":1,"sm":10,"store":null,"pickup":null,"store_id":"df4xrttfvy","__v":0}
]

But When I try to get this using angular service and store it in local storage. But When I check the LocalStorage data is not there.

This is the service.ts file

  getBookings(): Observable<Booking[]>{
    return this.http.get<Booking[]>('http://localhost:3000/booking/');
  }

and component.ts file

  ngOnInit() {
    this.bookingService.getBookings()
    .subscribe(data => this.bookings = data);

    localStorage.setItem('bookings', JSON.stringify(this.bookings));
  }

This does not give any errors in the console.

Please Tell me What have I done wrong hear.

Lahiru Mirihagoda
  • 1,113
  • 1
  • 16
  • 30

3 Answers3

1

Please change your ngOnInit() like this [i.e move your localStorage.setItem('bookings', JSON.stringify(this.bookings)); inside subscribe()] -

ngOnInit() {
    this.bookingService.getBookings()
    .subscribe(data => {
          this.bookings = data;
          localStorage.setItem('bookings', JSON.stringify(this.bookings));
     });
  }

You are trying to access this.bookings before it is filled by subscribe callback.

user2216584
  • 5,387
  • 3
  • 22
  • 29
0

Are there any data in the subscribtion? Try to do console.log(data) inside to check what comes from the backend.

Also please check if in app.module in providers array the service is imported.

Prezes
  • 21
  • 3
0

Adding to the answer, if you want the data outside subcription block you have to wait for the data for example try the below code,

ngOnInit() {
    this.bookingService.getBookings()
    .subscribe(data => {
          this.bookings = data;
     });
setTimeout(() => {
  localStorage.setItem('bookings', JSON.stringify(this.bookings));
},1000);
  }

but this is not the Async way we can use promise or async/await to achive Async way. let me know if you want we can discuss.

Raghul Selvam
  • 314
  • 2
  • 6