Angular 4.3 Http Client

时间:2017-09-28 23:49:45

标签: angular

请告知我如何用Angular 4.3替换新的HttpClient现有代码。我的问题是我想做深度解析并将服务类外的类型对象返回到Component。问题出在httpClient我无法将result.data作为UserModel返回

旧代码

组件

 this.loginService.authenticate(this.loginModel).then(
            res => { this.userModel = res;},
            error => { this.handleError(error);}
            );

服务类

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);

    }

经修订的服务类代码

public authenticate(model: LoginModel): Observable<UserModel> {
            return this.httpClient
                .post<UserModel>(this.controller, model)
                .catch(this.handleError);

        }

如何将response.result.data映射到Observable并返回。我不希望从我的类返回完整的响应对象,但只返回json的一部分作为类型对象。

1 个答案:

答案 0 :(得分:1)

您可以使用 rxjs 中的map运算符映射回复:

public authenticate(model: LoginModel): Observable<UserModel> {
  return this.httpClient
    .post(this.controller, model)
    .map(response => response.result.data as UserModel)
    .catch(this.handleError);
}

这会将响应数据返回为UserModel

相关问题