I have an http “interceptor” class to add my authorization headers to each call I make in my Ionic 2 application. I had it working fine with hard-coded authorization values for testing, but now I need to add the piece that gets the credentials from the local storage and I’m having issues figuring out how to return the right promise back to my service. I am getting the error “Cannot read property ‘map’ of undefined in [null]”.
I did not use Ionic v1 and don’t have a ton of experience with promises so I feel like there is something very simple I am missing. Both Ionic 2 and Angular 2 are pretty new so I haven’t been able to find the right solution online yet.
This is my code from my HttpClient interceptor class:
getAuth(){
return this.local.get("UserName")
.then(res =>
{
this.user = res;
return this.local.get("Token").then( res => this.session=res );
});
}
get(url) {
let headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
});
let params = new URLSearchParams('format=json');
this.getAuth().then(() => {
var authHeader = 'Basic ' + this.encode(this.user + ':{SessionToken}' + this.session);
headers.append('Authorization',authHeader);
return this.http.get(url, {
headers: headers,
search: params
});
});
}
The headers are correct and the call to .get works fine by itself. It’s only when I use it in my service and try to .map() that I get the error. This is how I call it from my service:
getTodos(id){
var url: string = this.global.APIUrl + "/" + id;
return this.httpClient.get(url)
.map((res)=> res.json());
}
If I console.log(this.httpClient.get(url)) at this point, it returns a promise, but the error indicates that it is returning “undefined”. Perhaps the HttpClient class isn’t compiling correctly but I’m not getting any errors from the class to know what is wrong.
Also, I have read several articles about using a .all() function to help clean up nested promises, but I haven’t found an example of how to do it in Ionic 2/Angular 2 specifically. I didn’t want to mess with it at the same time as this problem, but ideally, I would like to use something to stop the chaining if it exists.
And as a sidenote, I do have import ‘rxjs/add/operator/map’; in my service.