从HTTP Post到Typescript对象列表的转换响应

时间:2018-06-05 22:21:21

标签: json angular typescript typescript2.0

我已经调用了我的Web API。 API返回以JSON序列化的对象列表。我知道有很合理的方法可以将单个项目从JSON转换为typescript对象,但是我无法找到一种方法来进行这种转换,使其返回一个typescript对象列表。

我需要转换为typescript对象,因为我希望能够运行的对象中有一个函数,但是没有强制转换函数不存在。

以下是用于检索JSON的代码:

  findTrainPage(filter = '', sortOrder = 'desc', pageNumber = 0, pageSize = 15, departStart=null, departEnd=null, origStatusWhitelist=null): Observable<Train[]>
  {
    //retrieves a page of trains to display in the train list
    let url = AppUtils.backendApiUrl() + '/trainList/getPage';
    let requestBody = { 'filter': filter, 'sortOrder': sortOrder, 'pageNum': pageNumber, 'pageSize': pageSize, 'departStart': departStart, 'departEnd': departEnd, 'origStatusWhitelist': origStatusWhitelist };
    let options = new RequestOptions({ headers: AppUtils.commonHttpHeaders() });
    let headers = { headers: AppUtils.commonHttpHeaders() };
    return this.http.post(url, requestBody, headers).map(res => res.json()).catch(error => Observable.throw(error.json()));
  }

这是我想要投射的火车对象:

export class Train implements TrainInterface
{
  trainGUID: string;
  trainSymbol: string;
  createTime: string; //Should be formatted as a date, SQL table uses smalldatetime
  departTime: string;
  origStatus: OriginalStatuses;
  badGUIDFlag: boolean;
  trips: Trip[];

  private _evalStatus: EvalStatuses;
  get evalStatus(): EvalStatuses
  {
    return this.trips.reduce((min, p) => p.evalStatus < min ? p.evalStatus : min, this.trips[0].evalStatus);
  }
}

我查看了以下SO帖子:

JSON to TypeScript class instance?

Angular2 HTTP GET - Cast response into full object

1 个答案:

答案 0 :(得分:0)

创建响应包装类。这应该与API响应结构匹配。

export declare class ResponseWrapper<T> {
    static SUCCESS: number;
     data: Array<T>;
}

然后按如下方式映射响应。

 findTrainPage(filter = '', sortOrder = 'desc', pageNumber = 0, pageSize = 15, departStart = null, departEnd = null, origStatusWhitelist = null): Observable<any> {
//retrieves a page of trains to display in the train list
// let url = AppUtils.backendApiUrl() + '/trainList/getPage';
const url = 'assets/mockdata.json';
let requestBody = {
  'filter': filter,
  'sortOrder': sortOrder,
  'pageNum': pageNumber,
  'pageSize': pageSize,
  'departStart': departStart,
  'departEnd': departEnd,
  'origStatusWhitelist': origStatusWhitelist
};
let options = new RequestOptions();
return this.http.get(url)
           .map(res => res.json())
           .catch(error => Observable.throw(error.json()));

}

用法:

trainList : Train[];

  constructor(private trainService: TrainService) {
    this.trainService.findTrainPage()
        .subscribe(data =>{
        const  resultsWrapper:ResponseWrapper<Train> = data;
        this.trainList = resultsWrapper.data;
        });
       //   error => this.errorMessage = error);
  }

以下是经过测试的来源https://gitlab.com/supun/angular-stack-overflow-ref