The issue at hand
I am facing difficulty in utilizing the value returned by the Observable from getUserHeaders()
within my http.get
request.
Error encountered
Type 'Observable<void>' is not assignable to type 'Observable<Participant[]>'
Desired outcome
I aim to effectively use the output of my Observable returning function getUserHeaders()
as a headers
parameter inside the http
call, while solely returning the Observable of the http
request.
Prior code snippet
(which operated with hardcoded headers provided by getUserHeaders()
(rather than an Observable
or Promise
).
getAllParticipants(): Observable<Array<Participant>> {
return this.http.get('someUrl',
{headers: this.getUserHeaders()})
.map(response => {
return response.json();
});
});
}
Existing code implementation
Following advice from Chaining RxJS Observables from http data in Angular2 with TypeScript, I resorted to using the flatMap
method. (Please note that this current code triggers the 'current error' message).
getUserHeaders(): Observable<Headers> {
let headers: Headers = new Headers();
return NativeStorage.getItem("user").map(
data => {
headers.append('API_KEY', data.json().apiKey);
headers.append('DEVICE_ID', data.json().deviceId);
return headers
}).catch( error => {
console.log("error");
headers.append('API_KEY', 'TEST');
headers.append('DEVICE_ID', 'TEST');
return headers;
}
);
}
/** retrieves ALL the participants from the database */
getAllParticipants(): Observable<Array<Participant>> {
return this.getUserHeaders().flatMap( data => {
return this.http.get('someUrl', {headers: data}).map(response => {
return response.json();
});
});
}
Plunkr example (employing Promise instead of Observable)
http://plnkr.co/edit/A0tEB9EUodWQS6AnqrtH?p=info
(note: Observable.fromPromise()
was ineffective here, prompting me to create two methods returning promises -- now, I seek to utilize the value of getUserHeaders()
within the promise of getParticipants()
and still return the promise/observable originating from getParticipants()
, without affecting getUserHeaders()
.