Get value stored in local storage and use it in http calls


#1

i have a local storage which i have stored a value “123”

  this._storage.set("myvalue", '123');

I have tried retrieving it in the way below

private getStoredValue(){
this._storage
.get(“myvalue”)
.then(value => {
this._number = value // where _number is a global variable
console.log(’**number’, value)

                    });
    return this._number;
}

and i am trying to use it here, but i get a null,

getAPIDetails(){

 let id = getStoredValue() // I want to get 123 stored in local storage
  console.log(`${this._baseURL}myGetAPI/${id}`) // 
  return this._http.get(`${this._baseURL}/myGetAPI/${id}`)
             .map((res: Response) => res.json())
             .catch(this.handleError)

}

I dont know if i am right, please if i am wrong correct me


#2

Several problems here.

  • _number cannot be a global variable if you are accessing it via this. It is a property of the object containing getStoredValue().

  • You cannot return synchronous data out of a method that invokes an asynchronous operation. No matter what or how you try to do, you absolutely cannot return something you can assign directly to id from getStoredValue(). What you can do is to return a Promise and chain off it where it is used, but if getStoredValue() is private, it doesn’t really make sense to have it be a separate function.

getApiDetails(): Promisej<ApiDetails> {
  return Observable.fromPromise(this.storage.get('myvalue'))
    .mergeMap((id) => {
      return this._http.get().map(rsp => rsp.json());
    });
  • Don’t pass methods like handleError like this. You will inevitably end up losing execution context and getting baffled. Use a lexically scoped lambda instead:
let errorHandler = (err) => this.handleError(err);
.catch(errorHandler)

#3

you are the BEST., thank you so much.

Regarding

let errorHandler = (err) => this.handleError(err);
.catch(errorHandler)

if i have a lot of functions where i have to use the this.handleError, do i have to do the above line of code in every function?


#4

To elaborate, you only have to do so if handleError() has any references to this. If it doesn’t, and can safely be made static, then you’re OK doing it the way you’re currently doing it. The problems arise when you’re depending on this, because JavaScript is braindead on this topic. You can’t ever be certain what this is unless you manage it yourself, such as with either lambdas or arrow functions.


#5

You are a BOSS, thank you once again