我有一個查詢後端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的一些功能,可以讓我映射每一行來直接創建一個對象數組?
您想要將逗號分隔的字符串數組轉換爲TopTalkers數組,對嗎? – mchandleraz
您可以將轉換移入自己的工廠函數中,該函數接收一行並返回TopTalker以提高可讀性,但這非常重要。 – toskv
@toskv所以除了模塊化之外,還有什麼能夠做到的「自動化」呢? –