Home > Software design >  Angular - string with string value being passed as "[object object]"
Angular - string with string value being passed as "[object object]"

Time:07-25

TLDR: In my angular program I am passing a string as a parameter from the template. even though it has the correct value in the debugger, it is feeding through the functions (and ultimately back to the server) as "[object object]". I have tried JSON.stringify, and toString() but even after that, although they print correctly to console, they still pass through functions as "[object object]", and not as strings.

my code:

the object:

export interface Image {
    id: string;
    photoUrl: string;
    description: string;
}

relevant part of the component template:

<div  *ngFor="let pho of currentAnimal.images">
...
 <a  (click)="DeleteImage(pho.id)" >Remove Image</a>

the function in the component class:

 DeleteImage(photoId:string){
    
    //not sure why this is passing as an object:
    this.photoService.DeletePhoto(photoId).subscribe({

      error:(err)=>{console.log(err)},
      complete:()=>{
        let index = this.currentAnimal.images.findIndex(x=>x.id == photoId)
        this.currentAnimal.images.splice(index,1);
        this.toastr.success("Image has been deleted.");
      }
    })}

the function in my service passing it to the backend:

  DeletePhoto(PhotoId:string)
  {
   console.log("fired with: " {PhotoId}) 
   return this.http.delete(this.baseUrl 'deletePhoto/' {PhotoId});
  }

the above console.log consistently prints "[object object]", and that is also what is being passed to the backend. it didn't make any difference when I used JSON.stringify or toString() in the component function. in the debugger the string is just a string with it's correct value until passed to the backend.

any help would be greatly appreciated.

thanks!

CodePudding user response:

With {PhotoId} You are creating an object with the PhotoId shorthand field, which is the same like { PhotoId: PhotoId }. Simply remove the curly brackets.

  • Related