Angular HttpClient-rxjs映射-到类型数组 [英] Angular HttpClient - rxjs map - to an array of Type

查看:94
本文介绍了Angular HttpClient-rxjs映射-到类型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HttpClient.post调用,它们返回一个对象数组.

I have the following HttpClient.post call which return an array of Objects.

import { map } from 'rxjs/operators/map';

public getArray(profileId: number): Observable<any> {
    return this.http.post("/api/url", postObject, HttpSettings.GetDefaultHttpRequestOptions())
        .pipe(map(data => { 
          console.log(data); // logs (2) [{…}, {…}]
          return data;
        }));
}

我需要实例化对象数组.我不能只输入assert,因为我需要Thing构造函数来解析一些json和其他.

I need to Instantiate an Array of objects. I can't just type assert because I need the Thing constructor to parse some json and other.

基本上我想做的是:

.pipe(map(data => { 
      console.log(data); // logs (2) [{…}, {…}]
      return data.map(v => new Thing(v));
    }));

但是,我不能(据我所知),因为data是类型ArrayBuffer,并且不可迭代.我该如何实现?

However I can't (to my knowledge) because data is of Type ArrayBuffer and is not iterable. How can I achieve this?

推荐答案

实际上如何从服务器发送数据?是json还是其他?如果是json,请尝试在HttpClient的调用中进行指定(请参阅文档)使用options参数中的responseType:'json'.

How is the data actually sent from the server? Is it json or something else? If it is json try specifying that in the HttpClient's call (see documentation) using responseType:'json' in the options parameter.

import { map } from 'rxjs/operators/map';

public getArray(profileId: number): Observable<Thing[]> {
    var options = HttpSettings.GetDefaultHttpRequestOptions();
    options.responseType = 'json';

    return this.http.post("/api/url", postObject, options)
        .pipe(map(data => data.map(v => new Thing(v))));
}

这篇关于Angular HttpClient-rxjs映射-到类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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