Reputation: 1054
I've been going through rxjs and angular tutorials trying to understand Observables and how to chain them together. Based on everything I've read, the below code should work. But it doesn't and I don't understand why.
I'm trying to get a token from storage (faked that part out with getFakeToken method, because that compiles fine), then stuff that token in an httpHeaders object that should be wrapped in an observable that I can then chain together with another call to a web service and return that observable at the end of the day (which is why I'm not using a subscribe). I've taken the last call to the web service (that would use the http options built in the buildHttpOptions method) out, because the error is on the buildHttpOptions line.
I'm not sure I'm explaing everything properly, so here's another way of putting it: I'm trying to assynchronously get a token, insert that token into an httpOptions object, then (in the future iteration of the code that will be another ".pipe()" at the end of the return statement), use that to assynchronously call a web service and return the result wrapped in an observable. The first two parts (getting the token and inserting it into an object) are failing and I've included them in the code below.
Error message I'm getting:
[ng] ERROR in src/app/web-api/api.service.ts(57,50): error TS2322: Type '(token: string) => Observable<{ headers: HttpHe
aders; }>' is not assignable to type 'Observable<any>'.
[ng] Property '_isScalar' is missing in type '(token: string) => Observable<{ headers: HttpHeaders; }>'.
[ng] src/app/web-api/api.service.ts(67,31): error TS2345: Argument of type 'Observable<any>' is not assignable to parame
ter of type 'OperatorFunction<string, any>'.
[ng] Type 'Observable<any>' provides no match for the signature '(source: Observable<string>): Observable<any>'.
Code:
private getFakeToken(): Observable<string> {
return of("123abc");
}
getGetData(): Observable<any> {
let getToken$ = this.getFakeToken();
let buildHttpOptions$: Observable<any> = (token: string) => { return of(
{
headers: new HttpHeaders({
'Content-Type': 'application/json',
'authorization': token
})
})};
return getToken$.pipe(buildHttpOptions$);
}
Upvotes: 0
Views: 94
Reputation: 14139
You can use the map
operator to convert an object in an Observable to a different object. Then use switchMap
to chain your http request.
getGetData(): Observable<any> {
return this.getFakeToken().pipe(
map(token => ({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'authorization': token
})
})),
switchMap(headers => /* your http request that returns an Observable */)
);
}
Upvotes: 1