2017-12-27 555 views
0

我有一个查询后端API的服务。该API返回一组逗号分隔的文本行。这些列对应于我创建的TypeScript类中的属性。类是:将数组映射到Typescript/Angular中的对象

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的一些功能,可以让我映射每一行来直接创建一个对象数组?

+0

您想要将逗号分隔的字符串数组转换为TopTalkers数组,对吗? – mchandleraz

+0

您可以将转换移入自己的工厂函数中,该函数接收一行并返回TopTalker以提高可读性,但这非常重要。 – toskv

+0

@toskv所以除了模块化之外,还有什么能够做到的“自动化”呢? –

回答

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

你可以通过移动测绘工作进入人体简化您的构造函数签名一点点,就像这样:

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);   
}