【问题标题】:Angular http post response handlingAngular http post响应处理
【发布时间】:2018-05-29 20:12:18
【问题描述】:

我正在使用 ionic 3 / angular 开发应用程序,但遇到了一个小问题。我正在从服务中发出发布请求,并且正在尝试使用成功回调的返回值。 我收到以下转译错误:

Argument of type 'ArrayBuffer' is not assignable to parameter of type 'Occasion'. Property 'id' is missing in type 'ArrayBuffer'.

导致错误的代码:

this.api.post('occasions', occasion).subscribe(occasion => {
    this.myOccasions.unshift(occasion);
    this.myOccasionsChanged.next(this.myOccasions);
  },

列表this.myOccasions定义为private myOccasions: Occasion[];

我的api服务post函数定义为:

post(endpoint: string, body: any, reqOpts?: any) {
  if (!reqOpts) {
    reqOpts = {};
  }

  let headers = {};
  this.addAccessTokenToHeaders(headers);
  reqOpts.headers = headers;
  return this.http.post(this.url + '/' + endpoint, body, reqOpts);

}

你们能给我一些关于如何使类型一致的建议吗?当然,我的 POST 端点会返回一个 OccasionDto 来使用。 干杯!

【问题讨论】:

    标签: angular ionic-framework arraybuffer


    【解决方案1】:

    你可以映射 .post() 方法来转换数据并返回你需要的(一个场合)

    post(endpoint: string, body: any, reqOpts?: any): Observable<Occasion> {
       //etc...
       return this.http.post(this.url + '/' + endpoint, body, reqOpts);
       .map( data => {
          //do some transformation in the data, to return an `Occasion`
          const newData = /* something here, a function, a new Occasion(args), etc.... */
          return newData;
       })
    }
    

    【讨论】:

    • 感谢您的回复。我实际上创建了 ApiService,以便有可能为不同的实体重用方法(发布、获取、更新等)。所以我不想定义这个 post 函数返回 Occasion 的 Observable,因为这个函数也被设计为与其他实体一起使用
    • 你在做什么没有任何意义。您可以使用 HttpInterceptors 向您的请求添加您需要的标头(请看这里:medium.com/@ryanchenkie_40935/…),然后按照 REST 模式为每种对象创建您需要的服务。因此,您不必构建“通用”http 客户端,您可以构建特定的客户端,并通过拦截器“添加”标头。
    • 如何在 ArrayBuffer 和我的 Occasion 对象之间进行映射?
    • 谢谢,我现在找到了解决方案。我在拦截器上使用了你的建议(干杯!),但仍然保留了 apiService 以便为我处理参数等。我改用泛型类型,效果很好!查看我发布的答案
    【解决方案2】:

    我找到了我的问题的答案。我的处理方式如下:

    在我的 ApiService 中,我更改了方法签名,以便它们需要指定预期的返回类型并将响应类型设置为“json”,因为根据 angular 文档,http 客户端将返回 Observable&lt;Object&gt;

     post<T>(endpoint: string, body: any): Observable<T> {
        return this.http.post<T>(this.url + '/' + endpoint, body, {responseType: 
        'json'});
     }
    

    然后,当我调用我的 apiService 方法时,我会指定我想要退出的实体,如下所示:

    this.api.post<Occasion>('occasions', occasion).subscribe(result => {
        this.myOccasions.unshift(result);
        this.myOccasionsChanged.next(this.myOccasions);
      },
    

    我认为它很整洁,尽管如果有人有更清洁/更好的东西,请分享:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多