0

test-data component.ts

export class TestDataManagementComponent {
requirement = [] as any;
testDataFileType = "doc,docx,xls,xlsx,pdf,application/msword,application/msexcel,application/pdf";
isNotAccepted = false;

submitForm() {
var splitted = this.testDataFileType.split(",");
let payload = new FormData();

for (let i = 0; i < this.requirement.length; i++) {
      payload.append('requirements', this.requirement[i]);
    }

splitted.forEach(function (value) {
  for(let i = 0 ; i < this.requirement.length; i++) {
    if(this.requirement[i].name.split('.').pop() === value) {
      this.isNotAccepted = false;
      break;
    } 
    if(this.requirement[i].name.split('.').pop() !== value) {
      this.isNotAccepted = true;
      break;
}
}
});

ERROR TypeError: Cannot read property 'requirement' of undefined

Please help me figure out why 'requirement' is not defined and what is the best way to check each file's extension looping through the type array at once.

1 Answer 1

0

The problem you're facing is related to the reference of this.
this in JS is very confusing and one needs to be very cautious while writing the code. Here is the problem :

splitted.forEach(function (value) {
  for(let i = 0 ; i < this.requirement.length; i++) {
..... rest of the code 
}

You assume that in the class, this will refer to object/class. Well, it actually doesn’t. this is not defined to refer to the object that encloses it when you write your code. Instead, this refers to whoever called the code in which it’s being used. So Either you need to explicitly bind this to the method or use arrow function (which by default has class reference of this).

for example :

 splitted.forEach(value => {
      for (let i = 0; i < this.requirement.length; i++) {
        if (this.requirement[i].name.split(".").pop() === value) {
          this.isNotAccepted = false;
          break;
        }
        if (this.requirement[i].name.split(".").pop() !== value) {
          this.isNotAccepted = true;
          break;
        }
      }
      
    }); 

Here is a good read : MDN : this working example : Working example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.