Reputation: 293
Please advise how can I replace this existing code I have with new HttpClient with Angular 4.3. My issue is I want to do deep parsing and return typed object outside the service class to Component. The issue is with httpClient I'm not able to return result.data as UserModel
Old Code
Component
this.loginService.authenticate(this.loginModel).then(
res => { this.userModel = res;},
error => { this.handleError(error);}
);
Service Class
public authenticate(model: LoginModel): Promise<UserModel> {
return this.http
.post(this.controller, JSON.stringify(model))
.toPromise()
.then(response => response.json().result.data as UserModel)
.catch(this.handleError);
}
Revised Service Class Code
public authenticate(model: LoginModel): Observable<UserModel> {
return this.httpClient
.post<UserModel>(this.controller, model)
.catch(this.handleError);
}
How do I map response.result.data to Observable and return. I do not want to return complete response object from my class but only part of json as typed object.
Upvotes: 2
Views: 332
Reputation: 14267
You can map the response using the map
operator from rxjs:
public authenticate(model: LoginModel): Observable<UserModel> {
return this.httpClient
.post(this.controller, model)
.map(response => response.result.data as UserModel)
.catch(this.handleError);
}
This will return the response data as UserModel
.
Upvotes: 1