Home > Enterprise >  How to set model value in angular
How to set model value in angular

Time:11-11

I am trying to send a model to my backend from my frontend angular, this is how I define it in the class I want to use:

  documentsArray : DocumentModel

Now I have this method:

uploadFile(files: FileList | null): void {
      if(files){
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
        this.documentsArray.filename = file.name,
        this.api.saveDocument({body: 
         this.documentsArray        
        }).subscribe({
          next: data => console.log(data),
          error: error => console.log("your error: "   error)
        })
        console.log(this.documentsArray[0])
        console.log(JSON.stringify(this.documentsArray))
        }
      }
    }

But then I try to set this part:

    this.documentsArray.filename = file.name,

I am getting the following error:

TypeError: Cannot set properties of undefined (setting 'filename')

The model only has strings. Could someone tell me my error.

CodePudding user response:

First: you need to clarify whehter documentsArray is really an Array.

If yes, you have to specify the index at line:

this.documentsArray.filename = file.name,

As follow:

this.documentsArray[0].filename = file.name,

Guessing you want to set the first element name

If no, please show the entire file in a online code editor, such us CodePen or StackBlitz and share the link here

CodePudding user response:

documentsArray is undefined. Therefore you cant reach undefined.filename; you have to declare it like documentsArray = {};

  • Related