将数组映射到Typescript / Angular中的对象

时间:2017-12-27 19:48:00

标签: javascript angularjs typescript

我有一个查询后端API的服务。 API返回一组逗号分隔的文本行。这些列对应于我创建的TypeScript类中的属性。课程是:

export class TopTalker {
    constructor(
        public source: string,
        public protocol: number,
        public packets: number,
        public _percent: string,
        public _tally: string
    ) {}
}

我目前正在构建这些对象:

  getTopTalkers() {
    this._silk.topTalkers().subscribe(
        data => {
        let results = <any>[];
        results = data;
        this.topTalkers = <any>[];
        for (let row of results) {
          let thisTalker = row.split(/,/);
          let a = new TopTalker(
            thisTalker[0],
            thisTalker[1],
            thisTalker[2],
            thisTalker[3],
            thisTalker[4]);
          if(thisTalker.length > 1){   // Was getting a blank line
            this.topTalkers.push(a);
          }
        }
      console.log(this.largestTransfers);
      },
        err => console.error(err),
        () => console.log('Processed talkers')
        );
  }

以下是API返回的数据示例:

  

[ “8.248.215.242,6,7037358,53.111350,53.111350”, “8.248.209.245,6,2459465,18.561725,71.673076”, “192.168.2.86,6,604136,4.559450,76.232525”,“192.168.2.43 ,6,295422,2.229567,78.462092" , “192.168.2.39,6,254746,1.922583,80.384675”, “8.248.211.241,6,182544,1.377670,81.762345”,“192.168.2.69,6,180162,1.359693,83.122038 ”, “8.250.125.246,6,152862,1.153658,84.275697”, “8.248.213.243,6,93544,0.705982,84.981679”, “167.206.10.209,6,69862,0.527253,85.508931”, “”]

这有效,但感觉真的错了。是否有一些我缺少的Angular或TypeScript功能允许我映射每一行直接创建一个对象数组?

2 个答案:

答案 0 :(得分:1)

如果我正确理解你的代码,那么这样的东西应该非常接近你所追求的东西(并且更容易阅读,imo)

getTopTalkers() {
  this._silk.topTalkers().subscribe(
    results => {
      this.topTalkers = results.map((row, index, rows) => {
        let thisTalker = row.split(/,/);

        // Avoid blank lines by checking length
        if (thisTalker.length > 1) {
          new TopTalker(
            thisTalker[0],
            thisTalker[1],
            thisTalker[2],
            thisTalker[3],
            thisTalker[4]
          );
        }
      })
    },
    err => console.error(err),
    () => console.log('Processed talkers')
  );
}

理想情况下,我会探索将服务更新为不返回奇怪的逗号分隔字符串。

答案 1 :(得分:1)

您可以通过将映射工作移动到正文中来简化构造函数签名,如下所示:

class TopTalker {

    public source: string;
    public protocol: number;
    public packets: number;
    public _percent: string;
    public _tally: string;

    constructor(sourceRow: string[]) { 
        this.source = sourceRow[0];
        this.protocol = parseInt(sourceRow[1]);
        this.packets = parseInt(sourceRow[2]);
        this._percent = sourceRow[3];
        this._tally = sourceRow[4];
    }
}

这将从实例化代码中删除一些复杂性:

for (let row of results) {
      let thisTalker = row.split(/,/);
      let a = new TopTalker(thisTalker);
      this.topTalkers.push(a);        
}