When working with Angular, I encountered a situation where a string value was unexpectedly passed as "[object object]"

Summary: I am facing an issue in my angular program where I pass a string as a parameter from the template. Despite having the correct value in the debugger, it is being processed through the functions and eventually sent back to the server as "[object object]". I have attempted using JSON.stringify and toString(), however, even after these attempts, although they are correctly displayed in the console, they still go through the functions as "[object object]" instead of strings.

My code:

The object:

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

Relevant part of the component template:

<div class="col mb-5" *ngFor="let pho of currentAnimal.images">
...
 <a class="btn btn-outline-dark mt-auto" (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 sending 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 shows "[object object]", which is what gets passed to the backend. Using JSON.stringify or toString() in the component function did not make any difference. The string maintains its correct value until it reaches the backend system when debugging.

Any assistance on this matter would be highly appreciated.

Thank you!

Answer №1

When using {PhotoId}, you are essentially creating an object with the shorthand notation for the PhotoId field, which is equivalent to { PhotoId: PhotoId }. There is no need for the curly brackets; simply remove them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

Can you explain the distinction between the navigate function and routerLink feature in Angular 2?

As I go through the official Angular 2 tutorial, I noticed that it demonstrates using the navigate function in a way similar to routerLink. Can you explain the differences between these two methods and when it is best to use each? this.router.navigate([ ...

Insert elements within the <li> tags within an ordered list in an Angular application

Within the component.html file of my Angular project, I have the following code snippet: <li *ngFor="let activity of dto.activities | sortHistoryActivity; trackBy: trackByFn"> <span> <a (click)="scrollToHistoryActivity(activity. ...

Interpolating Attributes and Properties in Angular

My usual approach for property binding is as follows: <a [href]="myHref">Link</a> (where myHref represents a property in my Component class.) However, I have come across a different method on the Angular website where they use: <a href=" ...

Tips for instructing kysely key-gen to utilize basic data types for mapping database tables

While using the kysely-codegen tool to automatically create all models from my database, I have noticed a peculiar behavior. It seems to be adding a Generated type to every field instead of generating only number or boolean. Any idea why this is happening? ...

The specified attribute "matListItemTitle" is invalid in this context

Having trouble incorporating a list from Angular Material into an Angular project. WebStorm is showing the error mentioned in the title above. I came across the problem here, but in this scenario, I am unable to use matListItemTitle as a dynamic parameter ...

Can you explain the purpose of the "=" symbol in the function definition of "export const useAppDispatch: () => AppDispatch = useDispatch" in TypeScript?

Recently, while working on a React app that utilizes react-redux and react-toolkit, I encountered some TypeScript syntax that left me puzzled. export type RootState = ReturnType<typeof store.getState> export type AppDispatch = typeof store.dispatch e ...

Element in the iterator is lacking a "key" prop

import React from 'react' import { motion } from "framer-motion" type Props = {} export default function Projects({}: Props) { const projects = [1,2]; return ( <motion.div initial={{ opacity: 0 }} whileInVie ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

Tips for maintaining license comments in TypeScript 2.5

When creating JavaScript libraries using TypeScript v2.5 and tsc, it is important to include license comments in the built files. However, the removeComments configuration in the tsconfig.json file can remove certain comments, including license comments. ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

An issue has come up with Angular Jasmine where a property is being set on

Here is the code for my component: public save() { this.gridService.gridCellUpdated = false; } This is my Jasmine test code: class GridServiceMock { public gridCellUpdated = false; } let gridService: GridService; beforeEach( async(() => { T ...

The Vue store array declaration triggers a TS error stating that it is not assignable to a parameter of type never

I'm puzzled as to why this error keeps showing up: Argument of type '{ id: string; }' is not assignable to parameter of type 'never'. ... appearing at const index = state.sections.findIndex((section) => section.id === id); T ...

Validate Angular URLs to meet specific format

Is there a way to validate the format of my URL? The URL in question looks like this: www.example.com?rt=12365 I need to make sure that the URL follows this specific pattern: ?rt= number If it does, then I want to perform a certain action. Currently, I ...

Uncovering the websocket URL with NestJS and conducting postman tests: A step-by-step guide

Creating a mean stack application using NestJS involves utilizing websockets. However, testing websockets in Postman can be confusing. Typically, I test route URLs in Postman and get output like: "http://localhost:3000/{routeUrl}". But when it comes to tes ...

What is the best way to start a class instance within a stateless function component in React?

When following a stateful pattern, my usual approach is to initialize a helper class in the constructor and consume its methods in component lifecycle methods, as shown in the example below: class StatefulComponent extends Component { constructor(props) ...

Utilize Angular 7 to incorporate properties into a reusable template

Throughout my project, I have been using a template extensively: <div class="col-xs-6 event" *ngFor="let event of events"> <h1>{{ event.title }}</h1> <p>{{ event.content }}</p> </div> This template utilizes various ...

What steps should I take to fix the error message "Potential 'null' object"?

I'm encountering an error in my Typescript code within an Angular project. The error message reads: Object is possibly 'null' This error occurs on the following line of code: document.querySelector<HTMLElement>('.highlighted&apos ...

What is the best way to delegate the anonymous function logic contained within the subscribe() method?

Imagine you have a code block similar to this: constructor(private _http: HttpClient) { this.fetchUsers(5); } employees: any[] = []; fetchUsers(count: number) { this._http.get(`https://jsonplaceholder.typicode.com/users`).subscribe( ...

Dynamically assign values to object properties of varying data types using indexing

My goal is to dynamically update one object using another object of the same type. This object contains properties of different types: type TypeOne = 'good' | 'okay'; type TypeTwo = 'default' | 'one'; interface Opt ...