Search code examples
angularmongodbapigetlocal-storage

How to store data of mongodb through get request in local storage as an array


I have a service that sends a get request to fetch data from my mongodb collection and i want to store that incoming data into the localstorage as an array also.

API.SERVICE.TS

getStorageLocationsList(){
    this.setHeader();
    return this.http.get(this.localURL + 'storagelocation/view' + '?userplant=' + this.userplant , {headers:this.appHeader});
  }

COMPONENT.TS

this._api.getStorageLocationsList().subscribe(res => {
      this.storagelocationsList = res as Event[];
      //console.log(res);
    }, err => {
      console.log(err);
    });
//I want some more code here to store the data in res to the localstorage

Solution

  • this._api.getStorageLocationsList().subscribe(res => {
          this.storagelocationsList = res as Event[];
          //console.log(res);
          let storagelocationsList = ['A', 'B']; // suppose this is your api response
          localStorage.setItem('locationList', JSON.stringify(storagelocationsList));  
        }, err => {
          console.log(err);
        });
    

    For Fetch : JSON.parse(localStorage.getItem('locationList'));

    For more operations of localStorage check this