Search code examples
angularpapaparse

How to do http post with the results/data you get from the complete function in papaparse?


I am basically getting the following error

Cannot read property 'post' of undefined

My codes are the following:

export class AppComponent {
  constructor(public http: HttpClient, private papa: PapaParseService) {}
  results:any;
  createOrders(csvData) {
    this.http.post(environment.ordersUrl, {'order': csvData})
    .toPromise().then((data)=> console.log(data));
  }
  handleFileSelect(evt) {
    let file = evt.target.files[0];
    this.papa.parse(file, {
      header: true,
      dynamicTyping: true,
      complete: function(csvOrders) {
        this.http.post(environment.ordersUrl, {'order': csvOrders.data}).subscribe();
      }
    });
  }
}

Solution

  • The complete function you are calling has a different scope inside of it therefore different this.

    You could use either a fat arrow function:

    complete: csvOrders => {
        ...
     }
    

    Or bind this to the function:

    complete: function(csvOrders) {
      ...
    }.bind(this)