Angular:使用新的http客户端映射HTTP响应

时间:2018-04-10 04:39:48

标签: angular typescript

我的应用中有一个通用API服务,可以向后端发出这样的请求:

post<T>(url: string, jsonObject: object): Observable<T> {

    return this.http.post<T>(url, JSON.stringify(jsonObject));

}

我从我的组件中使用这样的方法并尝试将响应转换为特定模型:

this.apiService.post<SomeSpecificModel>('some/path/here', this.usernameForm.value)
                                        .subscribe(
                                            res => {
                                                console.warn(res);
                                            },
                                            () => {
                                                console.warn("error");
                                            }
                                        );

我的问题是API会返回如下内容:

{
    code: some-string,
    type: some-number,
    data: []
}

data属性是我想要在Angular中使用我的模型进行实体的实体。

我仍然希望能够访问我的组件中的codedata属性,但我不知道如何实现这一点。

我可以创建一个模仿API响应并具有通用数组属性的基本模型吗?像这样:

export class BaseModel<T> {
    code: string;
    type: number;
    data: Array<T>;
}

然后像这样投射?

this.apiService.post<BaseModel<SomeSpecificModel>>(...

我试过了,但我没有收到任何构建错误,但SomeSpecificModel上的属性未映射。

1 个答案:

答案 0 :(得分:2)

尝试一下这个。

您的服务代码

  public fetchData<T>(resourcePath: string):Observable<ResourceData<T>> {
    return this.http.get<ResourceData<T>>(resourcePath);
  }

您的组件代码

this.yourService.fetchData<DropDownDataItem>('/your/path/')
      .map((response) => {
        return {
          count: response.count,
          items: response.data
        };
      });

Inteface

export interface DropDownDataItem {
  id: number;
  name: string;
}

export interface ResourceData<T> {
  data: T[];
  limit?: number;
  offset?: number;
  count: number;
}

希望这有帮助

相关问题