Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Axios解析包装类型化数组_Javascript_Typescript_Api_Axios - Fatal编程技术网

Javascript 使用Axios解析包装类型化数组

Javascript 使用Axios解析包装类型化数组,javascript,typescript,api,axios,Javascript,Typescript,Api,Axios,我正在使用TypeScript和Axios。我有以下课程: class Item { private a: string = ''; private b: string = ''; public constructor(options: any = {}) { Object.assign(this, options); } } class Items { private items: Array<Item> = []; public constr

我正在使用TypeScript和Axios。我有以下课程:

class Item {
  private a: string = '';
  private b: string = '';

  public constructor(options: any = {}) {
    Object.assign(this, options);
  }
}

class Items {
  private items: Array<Item> = [];

  public constructor(options: any = {}) {
    Object.assign(this, options);
  }

  public getItems(): Array<Item> {
    return this.items;
  }
}
因此,我希望得到一个
Items
类,该类包含所有
Item
s,其中包含
a
b
c
应被忽略)

我尝试了以下方法:

Axios.get<Items>('path-to-backend-api').then((response) => {
  const items: Items = (new Items(response.data));
});
Axios.get('path-to-backend-api')。然后((响应)=>{
常量项:项=(新项(response.data));
});
但是,生成的
对象的内部数组为空。我还想在
response.data.items
数组中调用JS的
映射
,但无法使类型系统工作<代码>常量项:response.data.getItems()也失败。我尝试了十几种其他类型较少的方法,但找不到解决方案


我如何构造一个
数组好的,这里有很多东西要解包

传递给的泛型类型应表示传入反序列化数据的形状,即
响应。数据
您正在传递
,这是一个
您正在创建使用传入数据的新实例。它们是单独的,应单独声明

虽然可以使用,但这样做并不真正适合您的实现

response.data.getItems()
对于当前的实现是不可能的。如果您确实希望能够做到这一点(您可能不希望),您可以向中添加一个
transformResponse
函数,该函数在
Axios.get()的
response
中交付数据之前,从数据创建一个新的
class
实例

在对原始代码进行最小更改的情况下,我建议您如何正确键入并使代码更灵活:

接口项数据{
a:弦;
b:弦;
}
接口项数据{
项目:项目数据[];
}
类项实现ItemData{
a:字符串=“”;
b:字符串=“”;
构造函数(选项:ItemData){
分配(此,选项);
}
}
类别项目{
项目:项目[]=[];
构造函数(选项:ItemsData){
分配(this.items,options.items.map(item=>newitem(item));
}
getItems():项[]{
归还此物品;
}
}
get('path-to-backend-api')。然后((响应)=>{
常量项:项=新项(response.data);
//现在您可以使用类方法了
const list=items.getItems();
});

您是否尝试将json反序列化到您的模型中?首先,缩小问题范围。1.记录response.data。您是否收到任何东西?以所需格式(如camel-case vs-snake-case)?2.axios.get的泛型类型只是编译器的提示,它不会以任何方式强制执行。因此,您永远不会收到类的实例(将不建立原型链)。通过使用接口或类型而不是类来指定接收的数据类型来避免此陷阱。如果需要,请手动映射到类。1.是的,我记录了
resopnse.data
,这是预期的结果。2.我对TypeScript/Axios非常不熟悉,因此如果您认为有基于接口的解决方案,可以将其粘贴为答案。我不介意稍微修改一下代码。
Axios.get<Items>('path-to-backend-api').then((response) => {
  const items: Items = (new Items(response.data));
});