-2

I am using an api called ngx-pwa localstorage, which is kind of a wrapper around an indexeddb database. I have a service inside my Angular project that makes calls to the database called getItem:

getItem(key: string) {
    //let data: string;
    var data;
this.storage.get(key).subscribe((dataPassed) => {
   console.log("data passed was", dataPassed); // data is found but not returned
   console.log("typeof ", typeof(dataPassed))
   console.log("data is?")
   data = dataPassed as string
});
return data
}

when the method is called inside my angular component, nothing is returned, even though the item is found inside the subscribe method.

loadData(key) {
    console.log("storage from loaddb", 
this.storage.getItem(key)) // nothing is returned
}

What can I do to get ahold of that data?

Lester
  • 357
  • 3
  • 16
  • Your `data` will be returned before `subscribe` even gets called. That's why, you'll get `undefined` value returned by the method.`Observables` emit asynchronously. – Akash Aug 26 '20 at 13:55

2 Answers2

0

This is how async code work - you got your result in callback and it cannot be just returned in procedural manner (unless you will use async/await - but thats just a sugar)

So, instead of trying to return value - return observable and subscribe in the top layer

getItem(key: string) {
return this.storage.get(key).pipe(tap((dataPassed) => {
//just peeking
   console.log("data passed was", dataPassed); 
   console.log("typeof ", typeof(dataPassed))
   console.log("data is?")
});
}

loadData(key) {
    console.log("storage from loaddb", 
this.storage.getItem(key)).subscribe((val){do stuff with value}) 
}

ps. ther might be missing colon, or bracket somewhere.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

That wouldn't be the correct way to return data from an observable. You need to return the observable from the service and subscribe to it where the data is required. You could use various RxJS operators to perform operations on the emitted notification like console logging side-effects (using tap operator) and data transformations (using map operator).

Try the following

Service

getItem(key: string): Observable<any> {     // <-- return the observable
  return this.storage.get(key).pipe(
    tap((dataPassed) => {
      console.log("data passed was", dataPassed); // data is found but not returned
      console.log("typeof ", typeof(dataPassed))
      console.log("data is?")
    ),
    map(dataPassed => dataPassed as string)
  );
}

Component

data: string;

loadData(key) {
  console.log("storage from loaddb", 
  this.storage.getItem(key).subscribe(
    datapassed => {
      this.data = datapassed;
      // further statements that depend on `this.data` should be inside the subscription
    }
  );
}

You could find more info about asynchronous data and how to return them here.

ruth
  • 29,535
  • 4
  • 30
  • 57