Angular 16 - 将 PapaParse ngx 的结果传递给 API 提交

Angular 16 - Passing results of PapaParse ngx to API submission

提问人:Chris Docherty 提问时间:7/7/2023 更新时间:7/9/2023 访问量:28

问:

场景:导入 csv 以通过 API 加载到 DynamoDB。我有一个有效的 API,可以在通过表单输入时工作。现在我想通过 csv 批量加载。

我正在使用 ngx-papapare 来引入数据。我可以得到一个正确包含对象数组的结果对象,但是当它传递给我的 API 提交函数时,数组显示为空。

我添加了几个控制台日志并评论了它们显示的内容。正如你所看到的,在 papaParseCompleteFunction 的末尾,“clubsToLoad”数组包含来自 CSV 的四个数组对象。下面是数组中 1 个对象的控制台输出。

0
: 
clubID
: 
2
clubName
: 
"Newnham Archery Club"
[[Prototype]]
: 
Object

但是,在 SubmitToDB 函数中返回“data”对象时,该对象为空。

下面是 csv-loader 组件。

import {Component} from '@angular/core';
import { APIService, Club } from 'src/app/services/api/API.service';
import { Papa, ParseResult } from 'ngx-papaparse'; 

@Component({
  'templateUrl': './csv-loader.component.html',
  'selector': 'app-csv-loader'
})

export class CsvLoader {

  public clubsToLoad : Array<Club> = [];

  constructor(private api: APIService, private papa: Papa) {}

  parseCsvFile(file: File) {
    this.papa.parse(file, {
      header: true,
      dynamicTyping: true,
      skipEmptyLines: "greedy",
      worker: true,
      complete: this.papaParseCompleteFunction
    });
  }


  papaParseCompleteFunction(results: ParseResult) {
    console.log("Completed Results", results);
    this.clubsToLoad = results.data as Club[];
    console.log("clubsToLoad",this.clubsToLoad);
    /*clubsToLoad has correct array of 4 objects */
  }
  
  handleFileSelect($event: any) {
    const fileList = $event.srcElement.files;
    this.parseCsvFile(fileList[0]);
    }
 
  submitToDB(data: any){
    console.log(data);
    /* data array is now empty  - called from onclick event*/
    for (let d of data) {
        console.log(d);
        this.onCreate(d);
      }
      
      }

      public onCreate(club: Club) {

        this.api
          .CreateClub(club)
          .then((event) => {
            console.log('item created!');
          })
          .catch((e) => {
            console.log('error creating club...', e);
          });
      }
    }

下面是 html 中的 onlick 事件:

<div class="form-element">
        <button mat-raised-button color="primary" type="submit" class="button" (click)="submitToDB(clubsToLoad)">Submit File</button>
      </div>
数组 angular csv 解析

评论


答:

1赞 soniya ladhani 7/9/2023 #1

我想说的是,您可以直接使用 .ts 文件中的 this.clubsToLoad,而不是从模板发送数据,因为代码库位于同一文件中 可能是 angular 没有检测到 papaParaeCompletionFunction 发生的变化,您可以尝试使用 detectChanges 方法。我将尝试这些解决方案并在某个时候更新答案