将 HTTP 响应映射到 JSON,然后将 JSON 映射到模型的问题 [英] Issues mapping a HTTP response to a JSON and then mapping the JSON to a model

查看:72
本文介绍了将 HTTP 响应映射到 JSON,然后将 JSON 映射到模型的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个 http 响应映射到一个 JSON,然后将该 JSON 的一部分映射到一个 Ticket 接口,因为它有许多我在我的 Ticket 接口中不需要的值.我的应用程序编译没有任何问题,但是当我测试 REST 函数时,我收到以下运行时错误,我知道问题不在于后端,因为我能够成功地控制台记录响应.知道我在这里做错了什么吗?

I am trying to map a http response to a JSON and then map part of that JSON to a Ticket interface as it has many values I don't need in my ticket interface. My app compiles without any issues but when I test the REST function I get the below runtime error, I know the issue isn't with the backend as I'm able to successfully console log the response. Any idea what I'm doing wrong here?

My error:

    vendor.bundle.js:8137 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
    main.bundle.js:553 TypeError: res.json(...).map is not a function
        at MapSubscriber.project (main.bundle.js:1330)
        at MapSubscriber._next (vendor.bundle.js:42853)
        at MapSubscriber.Subscriber.next (vendor.bundle.js:4709)
        at XMLHttpRequest.onLoad (vendor.bundle.js:47289)
        at ZoneDelegate.webpackJsonp.749.ZoneDelegate.invokeTask (polyfills.bundle.js:2478)
        at Object.onInvokeTask (vendor.bundle.js:9228)
        at ZoneDelegate.webpackJsonp.749.ZoneDelegate.invokeTask (polyfills.bundle.js:2477)
        at Zone.webpackJsonp.749.Zone.runTask (polyfills.bundle.js:2245)
        at XMLHttpRequest.ZoneTask.invoke (polyfills.bundle.js:2540)


My code:

    retrieveTicket(barcode: string) : Observable<any> {
          return this.http.get(`${this.API_URL}POS/RetrieveTicket/${barcode}`, this.options)
          .map((res: Response) => res.json().map(ticket => {          
                Object.assign({
                    ResponseCode: ticket.ResponseCode,
                    CustomError: ticket.CustomError,
                    ticketDate: ticket.POSTicket.Date,
                    ticketTime: ticket.POSTicket.EndTime,
                    cashierName: ticket.POSBarCode.POSCashier_Name,
                    tranNo: ticket.POSTicket.TranNo,
                    tranValue: ticket.POSTicket.ScanValue,
                    securityChecked: ticket.POSBarCode.SecurityChecked
                }) as ITicket})         
          )
          .catch((error: any) => Observable.throw(error || 'server error'));
      } 


 my interface:

        import { BaseRequestInterface } from './base-request.interface';

        export interface ITicket extends IBaseRequest {
            ticketDate: string;
            ticketTime: string;
            cashierName: string;
            tranNo: string;
            tranValue: string;
            timeSincePurchase: string;
            securityChecked: boolean;

            export function setTicket(obj?: any) {
                super();
                this.ResponseCode = obj && obj.ResponseCode || null;
                this.CustomError = obj && obj.CustomError || null;
                this.ticketDate = obj && obj.ticketDate || null;
                this.ticketTime = obj && obj.ticketTime || null;
                this.cashierName = obj && obj.cashierName || null;          
                this.tranNo = obj && obj.tranNo || null;
                this.tranValue = obj && obj.tranValue || null;
                this.timeSincePurchase = obj && obj.timeSincePurchase || null;
                this.securityChecked = obj && obj.securityChecked || null;
            }


        }

my BaseRequest Interface:

//  Base request class that returns from BRMService API
export interface IBaseRequest {
    //  Public properties available
     BaseURI?: string;
     CustomError?: string;
     ProviderName?: string;
     RequestFormData?: string;
     RequestURI?: string;
     ResponseCode?: number;    
}

推荐答案

我们了解到我们只处理一个对象,而不是一个对象数组,因此将对象映射到 TicketModel 类型将如下完成(缩短):

We learned that we are dealing with just one Object, rather than an array of object, so mapping the object to type TicketModel would be done like the following (shortened):

retrieveTicket(barcode: string) {
   return this.http.get(...)
     .map(res => res.json())
     .map(res => ({ResponseCode:res.ResponseCode, CustomError:res.CustomError}) as TicketModel)
}

界面:

export interface TicketModel {
  ResponseCode: number; 
  CustomError:string 
}

演示

原帖:

不清楚您是为 TicketModel 使用类还是接口,无论如何我建议您使用接口 ;) 然后您可以简单地映射您的传入数据,例如(缩短版本):

Unclear if you are using a class or interface for your TicketModel, anyway I suggest you use an interface ;) Then you can simply map your incoming data like (shortened version):

.map((res:Response) => res.json().map(x => 
   Object.assign({ResponseCode: x.ResponseCode, 
                  CustomError:x.CustomError}) as TicketModel)))

如果您的响应是一个包含items 数组的对象,只需将items 添加到:

If your response is an object with an array containing inside items, just add the items in:

.... res.json().items.map( ...

这篇关于将 HTTP 响应映射到 JSON,然后将 JSON 映射到模型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆