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

a64a0gku  于 2023-07-31  发布在  Angular
关注(0)|答案(1)|浏览(93)

场景:通过API导入csv加载到DynamoDB。我有一个工作的API,当通过表单获取输入时可以工作。现在我想通过csv批量加载。
我用ngx-papapare来获取数据。我可以得到一个正确包含对象数组的results对象,但是当将它传递给我的API submit函数时,数组显示为空。
我添加了几个控制台日志,并对它们显示的内容进行了注解。正如您所看到的,在papaParseCompleteFunction的末尾,“clubsToLoad”数组包含来自CSV的四个数组对象。下面是数组中1个对象的控制台输出。

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

字符串
但是,当SubmitToDB函数中返回“data”对象时,它是空的。
下面是csv加载器组件。

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>

kqqjbcuj

kqqjbcuj1#

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

相关问题