2

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Editor shows red for response.result.data after map
Then try (response: any) => response.result.data as UserModel.
Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.