Reputation: 2465
Consider the following example:
login(context: LoginContext): Observable<Credentials> {
let credentials = JSON.stringify(context);
this.httpClient.post("http://localhost:64636/api/Account/login", credentials, {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
}).subscribe(response => {
let token = (<any>response).token;
const data = {
username: context.username,
token: token
};
this.setCredentials(data, context.remember);
return of(data);
}, err => {
});
}
Here what I am trying to achieve is to encapsulate the data that is received from the httpClient
and return it, but this is done after the execution of httpClient is complete. The compiler tells me that "a function whose declared type is neither 'void' nor 'any' must return a value" and rightfully so. My question is, how to resolve such issue when the parent observable must wait for the httpClient.post() observable to finish its task?
Upvotes: 1
Views: 506
Reputation: 73731
Use the map operator to modify the value returned by an Observable:
login(context: LoginContext): Observable<Credentials> {
let credentials = JSON.stringify(context);
return this.httpClient.post("http://localhost:64636/api/Account/login", credentials, {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
}).pipe(
map(response => {
let token = (<any>response).token;
const data = {
username: context.username,
token: token
};
this.setCredentials(data, context.remember);
return data;
})
);
}
Upvotes: 1