简体   繁体   English

如何创建具有日期索引的模型?

[英]How can i create a model with date index?

I want to access an API with Angular. 我想使用Angular访问API。 It gives me an array with a date as an index. 它给了我一个日期作为索引的数组。

I already tried to create a model, but unfortunately, it doesn't work. 我已经尝试创建一个模型,但不幸的是,它不起作用。 How do I have to change it? 我该如何改变它?

The API answer looks like this API答案如下所示

{
    "Information": {
        "Created": "2019-04-25",
        "Version": "1.2"
    },
    "Files": {
        "2019-04-26": {
           'name': 'file1',
           'size': 5,
        },
        "2019-04-25": {
            'name': 'file2',
            'size': 3,
        },
    ...
        }
    }

My model looks like this 我的模型看起来像这样

export class Model {
  'Information': {
    'Created': String,
    'Version': String,
  };
  Files: [

    {
     'Date': String,
     'name': String,
     'size': number,
    }
    ];

}

what you want here is an index signature , which looks like this. 你想要的是一个索引签名 ,看起来像这样。

export class Model {
  'Information': {
    'Created': string,
    'Version': string,
  },
  'Files': { 
    [date:string]: {
     'name': string,
     'size': number,
    }
  }
}

it's stating that class Model has a property Files which is an object with string keys and values that have a string property name, and a number property size. 它声明类Model有一个属性Files是一个带有字符串键和值的对象,它们具有字符串属性名称和数字属性大小。 This doesn't constrain that the keys have to match a certain date pattern, and I don't think there is a way to do that as far as I know. 这并不限制键必须匹配某个日期模式,据我所知,我认为没有办法做到这一点。

You can alternatively write a function that maps this response object into an object with a Files array where each object in the array contains the date. 您也可以编写一个函数,将此响应对象映射到具有Files数组的对象中,其中数组中的每个对象都包含日期。 That mapping function is a different question but the model would look like this: 该映射函数是一个不同的问题,但模型看起来像这样:

export class Model {
  'Information': {
    'Created': string,
    'Version': string,
  },
  'Files': { 
    'date': string, // could also type this as Date if you do the conversions
    'name': string,
    'size': number,
  }[]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM