Is there a way to call Storage synchronously?


#1

Hello, I am writing a service that consumes an API. The API requires a token be present on requests so that the user can be authenticated. Upon user login a token is given to the app which I store using the Storage module. Then I’m accessing it in all services which consume the API.

The problem is that the code which I’ve put in the constructor to load the token and id required for the authentication is asynchronous and so when the service is called it first executes the given method (getTask for example) and then the Token and Id get loaded in from the Storage module. So is there a way to wait for the token and id then start executing methods, or should I think of another way to do this?

Here is the constructor code:

constructor(private http: Http, private storage: Storage) {
        this.storage.get('token')
          .then(token => {
            console.log('Got token', token);
            this.headers.append('Token', token);
            this.storage.get('user')
              .then(
                user => {console.log('Got id', user.id);this.headers.append('Id', user.id)},
                error => console.error(error)
              );
          }, error => console.error(error));
    }

#2

You seem to be using the promise pattern properly in order to wait for the async to conplete (using then)

So not sure if async is your issue

Plae note that storage returns null if the key is not present in storage. Next your code does not show when you call the api using the headers

So can’t say what a solution is


#3

This is the code of my taskService. It has a method named getTasks, in which I use the headers when calling the API.

Since this is a service I inject it into a component, say TaskListComponent, and call the method getTasks to load all the tasks, however the request from the getTasks method gets sent before the headers are set in the constructor code, so the request is sent without the required Token and Id headers.


#4

I think there is no other way than asynchronously and like you said, you should “think another way” :wink:

Last part is for the joke, but I’m serious about the fact that storage is only accessible asynchronously, documentation for reference: