2017-12-27 1327 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);   
}