Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it.

Here is the User model:

export class User {
constructor(
    public id: number,
    public firstname: String,
    public lastname: String,
    public username: String,
    public password: String,
    public roles: Role
) { } }

And here is the Role model:

export class Role {
constructor(
    public id: number,
    public name: String
){}}

This is the Edit component:

export class AdminEditUserComponent implements OnInit {

  roles: Array<Role> = [];
  users = [];

  constructor(private _adminService: AdminService, private router: Router) { }

userForm = new FormGroup(
    {
      id: new FormControl(this._adminService.getUser().id),
      firstname: new FormControl(this._adminService.getUser().firstname, Validators.required),
      lastname: new FormControl(this._adminService.getUser().lastname, Validators.required),
      username: new FormControl(this._adminService.getUser().username, Validators.required),
      password: new FormControl(this._adminService.getUser().password),
      selectedRole: new FormControl(this._adminService.getUser().roles, Validators.required)
    }
  );

  getRoles(): void {
    this._adminService.getRoles().subscribe(
      result => {
        this.roles = result;
      }
    )
  }

  initfunc(): void {
    this.getRoles();
    this._adminService.getRoles().subscribe(
      result => {
        this.roles = result;
      }
    )
  }

  ngOnInit(): void {
    this.initfunc();

    this._adminService.getUsers().subscribe(users => {
      this.roles = [... new Set(users.map(user => user.roles))];
      console.log(this.roles);
  })
}

submitted: boolean = false;

  onSubmit() {
    let rolToUpdate = new Role(this.userForm.get("selectedRole").value, "");
    let userToUpdate = new User(this.userForm.get("id").value, this.userForm.get("firstname").value, this.userForm.get("lastname").value, this.userForm.get("username").value, this.userForm.get("password").value, rolToUpdate);

    this.submitted = true;

    this._adminService.putUser(userToUpdate).subscribe();

    setTimeout(() => {
      this.router.navigate(["/admin/users"]);
    }, 1000);
  }

  btnReturn() {
    this.router.navigate(["/admin/users"])
  }

}

Here is the html code for selecting the role:

        <div class="form-group">
            <select formControlName="selectedRole" class="form-control">
                <option *ngFor="let role of roles" ngValue="{{role.id}}" selected="{{role.id}}">
                    <div ngValue="role">{{role.name}}</div>
                </option>
            </select>
        </div>

When retrieving the role from the database, it appears in json format like this:

However, when attempting to update it, it looks like this:

This is the error message I receive when trying to update:

JSON parse error: Cannot deserialize instance of JSON parse error: Cannot deserialize instance of `java.util.HashSet<com.example.f1codingbackend.model.Role>` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.HashSet<com.example.f1codingbackend.model.Role>` out of START_OBJECT token↵ at [Source: (PushbackInputStream); line: 1, column: 161] (through reference chain: com.example.f1codingbackend.model.User["roles"])

It seems that the role array is not formatted correctly for updating. Can someone please provide insight on what might be wrong and how to resolve this issue?

Answer №1

One adjustment that should be made is to remove the <option> element within the <select> element in the HTML. Instead of using the <option> element, only {{ role.name }} should be used. Update your code as shown below:

<option *ngFor="let role of roles" ngValue="{{role.id}}">
    {{ role.name }}
</option>

When updating or changing the role, make sure to retrieve the ID of the new role (selected role).

let selectedRoleID = this.userForm.get('selectedRole').value;

To get the complete Role object:

use

let selectedRole = this.roles.find(role => role.id == selectedRoleID);

After obtaining the selectedRole, you can proceed with your HTTP request.

Answer №2

Essentially, when retrieving JSON data from the database, the roles are often multiple and displayed as an array in Angular. However, when attempting to update this data, only a single Role object is being passed. To resolve this issue, make sure to pass the Role object using an array structure like the following:

{ "firstName" : "David", "lastname" : "lim", "roles" : [{"id" : 1, "username" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d090c1b04092d0a000c0401430e0200">[email protected]</a>"}] }

Hopefully, this solution will assist you with your updating process.

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

Change Json data into a TypeScript class [ts]

I have the following JSON data: {"mapData":{"test":"success","publicKey":""},"statusCode":200,"message":null} How can I convert this JSON to a TypeScript class? The mapData contains anonymous values: It may be {"test":"success","publicKey":""} Or it m ...

Adding a parameter to each route by default."

In my Angular app, the route structure is as follows: const routes: Routes = [ { path: ':lang', children: [ { path: 'home', component: HomeComponent }, { path: 'dashboard', component: DashboardC ...

Using Java and Selenium, I am looking to target the parent element within a table using Xpath

My HTML page contains the following code snippet: <table class="report" style="width:100%"> <tbody> <tr> <th/> <th>Position Open <br> <span class="timestamp">27/ ...

Retrieve the element at the specified index in order to expand the XPath for a different List of WebElements

Looking to set up a List with the values of another List and their indexes from a loop I attempted the following snippet: List <WebElement> row = driver.findElements(By.xpath("//*[@id='row']")); for (int x=0; x<row.size(); x++){ String ...

Storing an Array in JSON Format to a File with PHP

{"Files": [ {"file_name": "Text_file.txt","path": "to_folder","file_id": "abc12345"}, {"file_name": "Img.jpg","path": "to_folder" ...

Streamline imports with Typescript

Is there a way to import modules with an alias? For example, I have an angular service in the folder common/services/logger/logger.ts. How can I make the import look like import {Logger} from "services" where "services" contains all my services? I've ...

Angular HTML layout designed for seamless interaction

<div class ="row"> <div class ="col-md-6"> Xyz </div> <div class ="col-md-6"> Abc </div> </div> Using the code above, I can easily create a layout with two columns. Th ...

Add a css class to a <div> that is created by an <ng-template> inside the <ngx-datatable-column> element

I am struggling to implement the display: flex style on the parent <div> containing my <span> However, since the <span> is dynamically generated by the ng-template of the ngx-datatable-column, I'm finding it challenging to apply thi ...

The class android.widget.Button is incompatible with android.widget.CheckBox and cannot be converted to it

I encountered an error in my Android project with the title "Register". Despite attempting solutions like checking checkbox casting and cleaning/rebuilding the project, the issue persists. The crash occurs when I click the "Register" Button after filling ...

What is the most effective way to refresh SCSS in a current Angular project?

I'm in the process of updating the SCSS version within my angular project. From the beginning, I selected scss in the angular cli for this project, so I have been using SCSS already. However, now I need to incorporate a spacing library that requires t ...

Establish a MongoDB river in Elasticsearch using the Java API

Currently, I am attempting to utilize the Java API to establish a new connection between MongoDB and ElasticSearch. The process is straightforward when using the REST API by sending a PUT request with the specified JSON code below: { "type": "mongodb", ...

A versatile Typescript array serving both as a storage for type information and input parameters

Our API is designed to handle a large amount of data, allowing users to control which properties are returned by using the fields parameter. The API definition looks like this: interface Foo { A?: string; B?: number; C?: boolean; D?: string ...

A step-by-step guide to extracting serialized data and displaying it in a table using unserialization in

Hello there, I go by the name of Tri. Currently, I am trying to store serialized data into a MySQL database using PHP. However, I am facing an issue with retrieving this data and displaying it in a table after unserialization. After unserializing the da ...

The correct method for sending an array to a shader in three.js

In my current project, I have a straightforward program in which I am attempting to pass an array of predefined values (essentially serving as a lookup table) to a shader. The corresponding code snippet looks like this: var table = []; for ( var ...

Struggling to extract the text from a list within a <ul> tag, but it seems to be grabbing only the initial item

Here is the structure of an unordered list View the structure of the unordered list I am attempting to extract the values of "var" and "time" as strings and store them in an ArrayList List<String[]> finalResult = new ArrayList<>(); This is w ...

Prevent automatic suggestions from appearing in Ionic app on Android

Our Ionic v4 (Angular, Cordova) app features form input fields (<ion-input>) like the example below: <ion-input formControlName="firstName" type="text" inputmode="text" autocapitalize="sentences"></ion-input> When running the Android ap ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

when compiling a list of objects, only selecting specific characteristics

I recently made the transition from C# to Java and am encountering a challenge. I am automating UI tasks using Selenium. My goal is to create a model for a list of elements on a webpage, extract their properties, and then work with these properties. For in ...

Change the background color of a span element dynamically

I am currently working on implementing dynamic background coloring for a span tag in my Angular view that displays document types. The code snippet provided is as follows: <mat-card *ngFor="let record of records"> <span class="doc ...

What is the best way to extract data from multiple FormControl instances using RxJS in Angular?

I am currently subscribed to three FormControl instances named filter1, filter2, and filter3. My goal is to fetch the values of all three whenever any one of them changes. I initially attempted to achieve this using combineLatest, but found that it only em ...