I have an http override class to add my authorization headers to each call I make in my Ionic2/Angular2 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 (using Ionic2 LocalStorage) and I'm having issues returning back to my service. I am getting the error "Cannot read property 'map' of undefined in [null]".
I feel like there is something very simple I am missing like a "return" or something with my nested promises (which I'd like to simplify if possible, but 1 issue at a time). Both Ionic 2 and Angular 2 are pretty new so I haven't been able to find the right solution online. I wasn't expecting LocalStorage to return a promise.
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. I do have import 'rxjs/add/operator/map'; in my service. This is how I call it from the service:
getTodos(id){
var url: string = this.global.APIUrl + "/" + id;
return this.httpClient.get(url)
.map((res)=> res.json());
}
When the browser refreshes, I get:
Cannot read property 'map' of undefined in [null]
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 that class to figure out what is wrong.