Home > Enterprise >  how to send a correct json to backend in angular
how to send a correct json to backend in angular

Time:11-11

I am sending an array object which right now looks like this in my console:

[{

}]

but I want to have it like this:

{

}

Could someone tell me how to change it, to my desired form? this is how my documentsArray looks:

  documentsArray = [];

This is how my code looks like this:

uploadFile2(files: FileList | null): void {
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result})
          console.log(this.documentsArray)
        }
    }

CodePudding user response:

You can access an array item using the index position:

const foo = [{ bar: 'baz' }, { quz: 'qux' }];

console.log(foo[0]); // only first item: `{ bar: 'baz' }`
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I.e.:

uploadFile2(files: FileList | null): void {
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result});
          // you can use the first object in the array
          console.log(this.documentsArray[0]);
        }
    }

CodePudding user response:

JSON specification is this:

[{ array1 }, {array2}, {other arrays}]

And this is the standard whay, why you would like to go outside the standard method?? Please note that in future if you want excange data with oter platforms, you will rebuild everithing, cause json array is with [ ] and json decode will fail if you don't have it, if you don't know how to handle the [ ] just temporary delete the first and the last characters from the writing/reading string, but is not so good..

  • Related