What is the best way to send an object to an Angular form?

I am facing an issue with my Spring entity, Agent, which includes an Agency object. When adding a new agent, I need to pass the agency as an object in the Angular form. While the backend code is functioning correctly, I am struggling to figure out how to properly pass the agency object to it. Currently, I am only saving the agency ID in the database, but I must specify the entire object when creating the entity.

@Entity
@Builder
@Getter
@Setter
public class Agent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false)
    private String firstName;

    @Column(nullable = false)
    private String lastName;

    private String phone;

    @Column(nullable = false)
    private String email;

    @ManyToOne
    @JoinColumn(name = "agency_id", referencedColumnName = "id", nullable = false)
    @JsonIgnore
    private Agency agency;
}

Here is the corresponding DTO:


@Getter
@Setter
@Builder
public class AgentDto {
    private Integer id;

    @NotNull
    private String firstName;

    @NotNull  
    private String lastName;

    private String phone;

    @NotNull
    @Email
    private String email;

    private Agency agency;
}

The save method for agents in the AgentService looks like this (where repo is the injection of JpaRepository):

 public AgentDto save(AgentDto agentDto) {
        Agent agent = mapper.mapToEntity(agentDto);
        Agent agentSaved = repo.save(agent);

        return mapper.mapToDto(agentSaved);
    }

The controller simply calls the save method:

@PostMapping
    public AgentDto save(@RequestBody AgentDto agentDto) {
        return service.save(agentDto);
    }

In my Angular project, the agent model goes as follows:

import { Agency } from "./agency";

export interface Agent {
    id: number;
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    agency: Agency;
}

This method is used in the agent service:

addAgent(model: any) {
    return this.http.post(this.baseUrl + 'agents', model);
  }

The TypeScript code for the "add-agent" component looks like this:

import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AgentService } from '../_services/agent.service';

@Component({
  selector: 'app-create-agent',
  templateUrl: './create-agent.component.html',
  styleUrls: ['./create-agent.component.css']
})
export class CreateAgentComponent implements OnInit {
  model: any = {};
  agencies: Agency[] = [];

  constructor(private agentService: AgentService, private router: Router, private _location: Location) { }

  ngOnInit(): void { this.loadAgencies(); }

loadAgencies() {
    this.agencyService.loadAgencies().subscribe(
      agencies => {
        this.agencies = agencies;
      }
    );
  }
  

  createAgent() {
    this.agentService.addAgent(this.model).subscribe(() => {
      this._location.back();
    })
  }

}

Finally, here is the HTML form section:

<form (ngSubmit)="createAgent()" autocomplete="off">

    <input 
      name="firstName"
      [(ngModel)]="model.firstName"
      class="form-control mt-3" 
      type="text" 
      placeholder="First name"
    >

    <input 
      name="lastName"
      [(ngModel)]="model.lastName"
      class="form-control mt-3" 
      type="text" 
      placeholder="Last name"
    >

   <input 
      name="email"
      [(ngModel)]="model.email"
      class="form-control mt-3" 
      type="text" 
      placeholder="E-mail"
    >

    <input 
      name="phone"
      [(ngModel)]="model.phone"
      class="form-control mt-3" 
      type="text" 
      placeholder="Phone"
    >

    <select name="agency" [(ngModel)]="model.agency" >
     <option *ngFor="let agency of agencies" [ngValue]="agency">{{ agency.id }}</option>
    </select>

    <button class="btn btn-success btn-sm mt-3" style="margin-right: 2%; box-shadow: 1px 1px grey;" type="submit">Add</button>

  </form>

I need assistance in passing the agency so that its ID gets saved in the database. I have attempted different approaches without success. What would be the correct way to achieve this?

Answer №1

Consider the following two options:


  1. Serialize the Agency object

To efficiently handle the 'agency' data, consider serializing the appropriate agency object before passing it along. This involves converting the agency object to a string using JSON.stringify method:

// Serialize (convert to string) appropriateAgencyForThatAgent:Agency

let agencyString:string = JSON.stringify(appropriateAgencyForThatAgent);

In the backend controller responsible for processing the request (AgentDto save), you can then parse this string back into an 'Agency' object: Learn more about parsing JSON in Java here


  1. Pass the id Agency and process it in the back

Alternatively, rather than sending the entire 'Agency' object, you can send just the ID of the agency as a number. In the backend controller for AgentDto save, retrieve the corresponding agency based on this ID and include it accordingly.

This approach simplifies the data transfer process and streamlines the handling of agency information.

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

Checkbox offering a tri-state option

Seeking help on creating a checkbox with three states. I have implemented a method to toggle between these states upon clicking. However, the issue is that this method is only triggered after the HTML changes. As a result, the checkbox's navigation be ...

Verify the login details of a distant website using Angular

Currently, I am in the process of developing a user interface for Hacker News using Angular 7. Typically, I rely on public APIs for various functionalities, but unfortunately, login services are not accessible through these APIs. In order to address this ...

Confirming that the NGRX Dictionary value is set

After upgrading from Angular 7.1.4 to 8.2.0 and Typescript from 3.1.6 to 3.5.3, I encountered an issue with identification of array items. Prior to the upgrade, TypeScript correctly recognized that the array item was not undefined. However, post-upgrade, ...

The string is being added to an array twice

I am managing two sets of lists where strings will be transferred between them. One set contains a list of strings for searching purposes. The other set contains the same list of strings but is not used as a filter. The second set functions in a similar ...

saveToPhotoAlbum functionality not functioning as expected on both Android and iOS platforms

Everything in my ionic 4 app seems to be working fine, from taking pictures with the camera plugin to uploading them to a remote server. I can even access images from the gallery on another page. However, there's one issue that I can't seem to fi ...

What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function: public GetExercisePosts(user: User): ExercisePost[] { const exercisePosts = new Array<ExercisePost>(); firebase.firestore().collection('exercise-posts').where('created-by&apo ...

Angular model remains static when incorporated within the document.addEventListener() attribute

Can anyone help me figure out why my attempt to update the model name this.name on click inside document.getElementById('source-selection').addEventListener is not working? Surprisingly, a simple alert within that function does trigger successful ...

Tips for exporting a React Component without using ownProps in a redux setup with TypeScript

I'm currently working on a project using typescript with react-redux. In one of my components, I am not receiving any "OwnProp" from the parent component but instead, I need to access a prop from the redux state. The Parent Component is throwing an er ...

The type mismatch issue occurs when using keyof with Typescript generics

One of the challenges I am facing is related to an interface that stores a key of another interface (modelKey) and the corresponding value of that key (value): interface ValueHolder<T, H extends keyof T> { modelKey: H; value: T[H]; } My objectiv ...

OnDrop event in React is failing to trigger

In my current React + TypeScript project, I am encountering an issue with the onDrop event not working properly. Both onDragEnter and onDragOver functions are functioning as expected. Below is a snippet of the code that I am using: import * as React from ...

Determining the generic type argument of a class can be unsuccessful due to the specific properties within that class

Why is it that Typescript sometimes fails to infer types in seemingly simple cases? I am trying to understand the behavior behind this. When Typescript's Type Inference Goes Wrong Consider the scenario where we have the following class declarations: ...

Firebase authentication link for email sign-in in Angularfire is invalid

Currently, I am utilizing the signInWithEmailLink wrapper from AngularFire for Firebase authentication. Despite providing a valid email address and return URL as arguments, an error is being thrown stating "Invalid email link!" without even initiating any ...

Troubleshooting: The issue of ngModel being undefined in Angular2 with the <input> element

I am currently working with Angular2 and a modified version of Semantic-UI that includes a calendar module. I am utilizing the `calendar` and `dropdown` functionalities: constructor() { setTimeout(() => { jQuery('.ui.dropdown').dr ...

Utilizing FileInterceptor with a websocket in NestJs: A Step-by-Step Guide

Is it possible to implement this on a websocket, and if so, how can I achieve that? @UtilizeInterceptors( DocumentInterceptor('image', { location: '../data/profileImages', restrictions: { size: byte * 10 }, ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

Displaying a pair of items side by side using Angular's ngFor

I've encountered an issue with my code related to displaying a 4 by 8 grid using the ngFor command. Below is the snippet of the code in question: <div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)"> <ng-cont ...

What could be the reason for the absence of the mandatory message while using the mat datepicker

Here is a template I am currently using: <input type="text" class="form-control" name="my_date" [matDatepicker]="myDatepicker" #myDate="ngModel" [(ngModel)]="myDateValue" id="my_date" required> &l ...

When completing a form submission, make sure to eliminate the %5B%5D from the

Whenever I submit a form with multiple checkboxes that share the same name, the resulting URL format is as follows: www.example.com/search.php?myvalue%5B%5D=value1&myvalue%5B%5D=value2 Is there a method to eliminate the %5B%5D in the URL and make it m ...

Using CKEditor5 to Capture and Edit Key Presses

I'm currently working on capturing input from a CKEditor5 within an Angular application using TypeScript. While I am able to successfully display the CKEditor and confirm its presence through logging, I am facing difficulties in capturing the actual i ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...