Angular2 - Use the value of the return observation method in another observable

Problem

I don't know how to use the value of the currently returned Observable getUserHeaders() in my http.get .

Current error

Type 'Observable<void>' is not assignable to type 'Observable<Participant[]>'

Expected Result

Ability to use the value of the returned Observable getUserHeaders() method as a headers attribute in an http call. While returning an http Observable call.

Previous code

(which worked with the header headers returned by getUserHeaders() (rather than Observable or Promise ).

 getAllParticipants(): Observable<Array<Participant>> { return this.http.get('someUrl', {headers: this.getUserHeaders()}) .map(response => { return response.json(); }); }); } 

Current code

There is a RxJS chain Observed data from http data in Angular2 with TypeScript answer I came up with the flatMap method. ( note this code is currently throwing a "current error")

 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 (promise instead of observable)

http://plnkr.co/edit/A0tEB9EUodWQS6AnqrtH?p=info

(note: Observable.fromPromise() does not work here, so I created two methods that return promises - now I want to use the getUserHeaders() value getUserHeaders() promise and still return the promise / observable getParticipants() and nothing from getUserHeaders()

+6
angular typescript observable rxjs ionic2
source share
1 answer

Change your getUserHeaders() to look like this:

 getUserHeaders(): Observable<any> { return Observable.of(NativeStorage.getItem("user"); } 

Then create a header object in getParticipants() . This way you can save flatMap

+4
source share

All Articles