"Sending an Angular post request results in the transmission of an [object Object

I am a beginner in angular and currently involved in a project using angular 6 with Spring Boot 2. Here is the TypeScript class I am working with:

export class Partner {

  constructor
  (
    public id: number,
    public name: string,
    public email: string,
    public phone: string,
    public address: string,
    public picture: string,
    public latitude: number,
    public longitude: number,
    public horary: string,
    public comment: string,
    public specialOffer: boolean,
    public offer: string,
    public location: Location,
    public tripAdvisorLink: string,
    public type: Type,
    public country: string,
    public hotWords: HotWord[],
  ) {}
}

For instance, when creating a partner, a Location must be selected.

In my HTML file, it looks like this:

<div class="form-group">
  <label for="partner_location" class="form-control-label" required>Choose location <span class="text-danger">*</span></label>
  <select id="partner_location" class="form-control" [(ngModel)]="partner.location" name="partner_location">
    <option *ngFor="let location of locations" [value]="location">{{location.name}}</option>
  </select>
</div>

In my create partner component:

export class CreatePartnerComponent implements OnInit {

  partner = new Partner(undefined, '', '', '', '', '', undefined, undefined, '', '', false, '', null, '', null, '', null);
  types: Type[];
  locations: Location[];
  message = '';
  error = '';

  constructor(
    private getPartnersService: GetPartnersService,
    private getTypesService: GetTypesService,
    private getLocationService: GetLocationsService
  ) {}

  ngOnInit() {
    this.loadInitialData();
  }

  loadInitialData() {
    this.getLocationService.getLocations().subscribe(locations => this.locations = locations);
    this.getTypesService.getTypes().subscribe(types => this.types = types);
  }
  
  onSubmit() {
    console.log('Partner = ' + JSON.stringify(this.partner));
    this.getPartnersService.createPartner(this.partner)
      .subscribe(partner => {
        if (partner.id !== undefined) {
          this.showMessage();
          window.scrollTo(0, 0);
        } else {
          this.showError();
          window.scrollTo(0, 0);
        }
      });
  }

This is my create partner method:

const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}) };

  createPartner(partner: Partner): Observable<Partner> {
    const url = `${baseUrl}/partner/add`;
    return this.http.post<Partner>(url, partner, httpOptions)
      .pipe(catchError(HandleError.handleError<Partner>('createPartner')));
  }

An issue arises in Spring where it cannot create Location from [Object object]. The output of

console.log('Partner = ' + JSON.stringify(this.partner));
shows:

Partner = {"name":"Test production","email":"you@example.com","phone":"32489836733","address":"brolekestraat","picture":"","latitude":"55","longitude":"1.23424324","horary":"9 - 18 every day","comment":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaa","specialOffer":true,"offer":"5%","location":"[object Object]","tripAdvisorLink":"http://brol.be","type":"[object Object]","country":"Belgium","hotWords":null}

It seems that the http post request sends location : [object Object]....

How can I resolve this issue?

Answer №1

In order to ensure proper data binding, the partner.location variable is assigned a string value because the option element's value is bound using [value]. To bind the option value to an object, you should utilize [ngValue]:

<select id="partner_location" class="form-control" [(ngModel)]="partner.location" name="partner_location">
  <option *ngFor="let location of locations" [ngValue]="location">{{location.name}}</option>
</select>

The Angular documentation explains:

If your option values are simple strings, you can bind to the normal value property on the option. If your option values happen to be objects (and you'd like to save the selection in your form as an object), use ngValue instead.

Answer №2

The issue arose from how the value of the option was bound. The correct approach to binding is as follows:

<option *ngFor="let location of locations" [ngValue]="location">{{location.name}}</option>

Feel free to take a look at my StackBlitz demo to see this solution in action: https://stackblitz.com/edit/angular-pckh2b

Answer №3

[Subject subject] signifies that the information is not formatted in a way that can be easily read from the document. It requires encoding and decoding to be processed.

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

Angular fails to refresh object array when new object is added

Currently, I am immersed in a project that involves using angular-google-map (agm) and incorporating various polygons to represent different elements. However, I have encountered an issue where my object array fails to update when I attempt to draw on the ...

Enhancing Skylinkjs functionality using Typescript

Hello fellow developers, I am new to using typescript and currently experimenting with incorporating SkylinkJS into my project. Can anyone guide me on the best practices for utilizing an npm library with TypeScript? If you are interested in checking out t ...

Tips for initializing constructor arguments using JSON during object instantiation in TypeScript

Let's consider a scenario where we have the following class: export class PersonInformation { constructor( public firstName: string = "", public lastName: string = "", public middleName: string = "", ) { } } Now, we&a ...

Can the order of event bubbling be altered in JavaScript?

I have three boxes in my HTML, each with its own click events. Currently, when I click on a child element, event bubbling occurs in the order of C->B->A. However, I am curious to see if it's possible to change the event bubbling order to C-> ...

Exploring the power of EJS with conditional logic

Can someone help me figure out why EJS is not evaluating to the else branch in my code? I'm using EJS version 3.1.5 with express version 4.17.1 and typescript. ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12 10| </head> 11| & ...

Issue with installing firebase-tools through macOS terminal

Having trouble installing firebase-tool for CLI on macOS. Attempts to install using $ sudo npm install -g firebase-tools are resulting in failures. I encountered errors related to permission denied when trying to access directories even with 'sudo&a ...

RXJS - Leveraging BehaviorSubject's value property for optimal usage

I'm curious about the proper use of behaviorSubject.value. In a discussion on Stack Overflow, it was mentioned that values should ONLY be obtained through subscription. One scenario where it makes sense to me is when I need to determine the next valu ...

Error encountered in Typescript: The property 'prevUrl' is expected to be present in the props object, but it appears to be missing

When trying to access the props.prevUrl property, the following error is encountered: Property 'prevUrl' does not exist on type '{ nextUrl: string; } | { prevUrl: string; nextUrl: string; } | { prevUrl: string; confirm: () => void; }&apos ...

How can TypeScript and MobX work together using Set()?

I'm encountering errors while trying to implement Set() in my Grocery Shopping app using MobX with TypeScript. I have a simple setup with defined types in types.ts: types.ts export type Item = { name: string; instock: number; price: number; }; ...

Rearranging data received from an Observable

TL;DR I am working on an Angular app where I need to shuffle an array of names retrieved from a network request and ensure that each group of 6 names selected is unique. However, I noticed duplicates in the selections. Here's a CodePen example using o ...

How to prevent users from accessing the app through standard web browsers in an Express/Electron application

My setup involves an express server that serves my angular front end at http://localhost:9000 Utilizing electron as a desktop client is part of my project. I am aiming to restrict users from accessing the application through any browser except electron. ...

Help! I keep getting the NullInjectorError in the console saying there is no provider for Subscription. Why is this happening?

Here is the code snippet I'm working on within a component: import { Component, OnDestroy, OnInit } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-home', templateUrl ...

The failure of an Angular2 HTTP GET request with a header

Attempting to make a simple get request using angular2 http, like this: (including the token retrieved from a post to my api) let idToken = localStorage.getItem('id_token'); let authHeader = new Headers(); if (idToken) { authHeader.append(&a ...

TypeScript: The capability to deduce or derive values for a type from a constant object literal that is nested with non-distinct keys

I'm trying to figure out a way to utilize TS/IDE to display specific literal values from a style guide object, instead of just the inferred type. Here's an example: const guide = { colors: { black: { medium: "#000000", } ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

"The issue persists in Angular 5 - I am using ngOnInit to fetch my object from firestore, but surprisingly the view does not reflect any

After working with Angular 5 and Firestore, I encountered an interesting issue. When retrieving my document and checking it using console.log(this.assets) in ngOnInit(), everything seems fine. However, a strange thing happens during a page reload: if I qui ...

Create a TypeScript array of objects that mirrors a Java List<Map<String, String>>

In my Java function, the argument type is List<Map<String, String>>. To perform a fetch call from a TypeScript file, I need to declare a variable whose type corresponds to List<Map<String, String>>. As TypeScript does not have a bu ...

Angular 9 - Button unable to be clicked under certain conditions

I have a webpage that contains a lot of information, and I would like to make it easier for the user to show/hide specific parts by clicking on buttons. Check out this stackblitz to see what I've done. Here's a brief summary of the code: <but ...

Tips on maintaining continuous ng serve to keep Angular 2 application running indefinitely

I am running an Angular 2 application using the command ng serve --host ip address. Once executed, it starts at the default port and displays the following logs: Hash: ddb0ab205ea65648a918 Version: webpack 2.1.0-beta.25 Time: 17516ms Asset ...

Passing a username and password to an API in Angular 6: Step-by-step guide

Can someone assist me with this problem? I am struggling to pass the username and password in my API request for a list of homes. Every attempt I've made has resulted in an unauthorized access error. How do I correctly include the user credentials (pe ...