Struggling with managing asynchronous data retrieval from local storage in my Angular2/ionic2 app.
The code snippet I'm using:
request(args) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
// Retrieve token from local storage, add to header if available
this.storage.get('token').then((value) => {
headers.append('Authorization', 'Token ' + value);
});
args = args || {};
var url = this.API_URL + args.url;
var method = args.method;
var data = args.data || {};
var options = new RequestOptions({headers: headers, withCredentials: this.use_session});
return new Promise((resolve,reject) => {
if (method == 'GET') {
this.http.get(url, options)
.map(res => res.text())
.subscribe(
(data:any) => {
resolve(data);
},
(err:any) => {
data = {};
data['status'] = 0;
data['non_field_errors'] = ["Could not connect to server. Please try again."];
data['error'] = err;
reject();
},
() => {
}
);
}
});
}
The code calling the request function:
authenticationStatus(){
return this.request({
'method': "GET",
'url': "/user/"
})
.then((data:any) => {
console.log('****** authenticationStatus: GET /user/ SUCCESS');
});
}
And then it's triggered like this:
this.djangoAuth.authenticationStatus()
.then((data:any) => {
this.loggedIn = true;
this.enableMenu(true);
this.root = PhotoPage;
},
(err:any)=>{
this.loggedIn = false;
this.enableMenu(false);
this.root = LoginPage;
});
Struggling with understanding nested promises and modifying the code to ensure that the result of this.storage.get("token")
is added to the header before being used below. Need help with chaining promises effectively.