将数组中的值附加到BehaviorSubject

时间:2017-03-26 18:45:02

标签: angular typescript rxjs observable behaviorsubject

我有一个EvaluateHistoryItem []类型的BehaviourSubject历史记录$。在uploadFile方法中,我用逗号分割上传的.txt文件,然后将它们推送到resultSet []。我想将resultSet []中的值附加到history $ BehaviorSubject。

我是RxJS的新手,发现它很复杂(仍然在努力)。我将不胜感激。

我试过类似这样的东西,但它不正确,因为我不想映射,但附加新值(我认为它应该是combineLatest的东西):

 history.map(a => {
                a.saved = this.convertToBool(resultSet[0]);
                a.evaluate = resultSet[1];
                a.result = resultSet[2];
                a.runTimeMs = Number(resultSet[3]);
                a.tags.map(tag => tag.value = resultSet[4]);

            });
 this.history$.next(history);

PS。对不起,如果问题的标题不好。

这是我的代码:

interface EvaluateHistoryItem {
evaluate: string;
error?: string;
result?: string;
runTimeMs?: number;
saved?: boolean;
}

export class EvaluateComponent implements OnInit, AfterViewInit {
   ...  ...  ...
   ...  ...  ...
   public history$ = new BehaviorSubject<EvaluateHistoryItem[]>([]);
   ...  ...  ...
   public uploadFile(element: any) {
       let uploadedFile = document.getElementById('uploadedFile');
       let files: File[] = element.srcElement.files;
       let file: File = files[0];

       let reader = new FileReader();

       let resultSet: string[] = [];

       reader.onloadend = (result) => {
           // replace new lines with commas and then split upon commas but not the ones inside quotes
           let columns: string[] = reader.result.replace(/\n/g, ',').split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

           for (let i = 0; i < columns.length - 1; i++) {
               resultSet.push(columns[i]);
           }
       };

    let history: EvaluateHistoryItem[] = this.history$.getValue();
    // ... here I need to map values from resultSet
    // ....
    this.history$.next(history);
}  

1 个答案:

答案 0 :(得分:1)

我在您的问题中阅读的关键字为skipbufferCount

resultSet
  .skip(4) /* first four emissions */
  .bufferCount(4)
  .map(buffer => ({
    save: buffer[0],
    evaluate: buffer[1],
    result: buffer[2], 
    runTimeMs: buffer[3] 
  }))
  .subscribe(console.log);