Hi all, first time using Ionic! I’m trying to wrap my head around the promise/observable patterns and I seem to be coming up short. I’m attempting to create a wrapper for the Angular 2 HTTP object, which basically just adds the proper authorization headers from SqlStorage and sends along the same Observable, which the caller can subscribe to as if it were the original HTTP client, like this:
this.http.get("http://localhost:3000/confirm_auth_token")
.subscribe(
data => console.log(data.json())
//...
)
)
Here’s what I have so far:
import { Injectable } from '@angular/core';
import { Http, Headers, Response, HTTP_PROVIDERS } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Storage, SqlStorage } from 'ionic-angular';
/*
A custom wrapper to include headers for API authentication.
Header info is stored in local storage.
*/
@Injectable()
export class HttpClient {
headers : Headers;
constructor(private http: Http) {
}
buildHeaders(){
let headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
})
let storage = new Storage(SqlStorage);
return storage.get("user").then(
(u) => {
let user = JSON.parse(u);
headers.append('X-User-Email', user.email);
headers.append('X-User-Token', user.authentication_token);
return headers;
}
)
}
get(url) {
return this.buildHeaders().then(
(headers) => {
return this.http.get(url, {
headers: headers
})
}
)
}
}
However, I’m getting the following error:
Error TS2339: Property 'subscribe' does not exist on type 'Promise<Observable<Response>>'.
So it appears I’m returning the Promise, instead of the Observable this.http.get() request.
Can I somehow “unwrap” the Promise? Is there a better way to do this?
Thank you!