Send two unique GUID parameters to an API using Angular

I have created an API for following a user. This method requires two parameters, which are both GUIDs. Here is the code snippet:

// Follow user
[HttpPost]
public async Task<ActionResult<Guid>> FollowUser([FromBody] Guid user_gd, Guid user2_gd)
{
  if (ModelState.ErrorCount > 0)
  {
    return BadRequest();
  }
  var followedUser = await _user.FollowUser(user_gd, user2_gd);
  return Ok(followedUser);
}

The manager in the API:

public async Task<bool> FollowUser(Guid user_gd, Guid user2_gd)
        {
            var followUserQuery =
                @"
                    insert into userbind(gd, user_gd, followed_user_gd, date_followed) 
                    values(@_gd, @_user_gd, @_followed_user_gd, @_date_followed)
                ";
            await PostQuery(followUserQuery, new
            {
                _gd = GenerateGd(),
                _user_gd = user_gd,
                _followed_user_gd = user2_gd,
                _date_followed = DateTime.Now
            });

            return true;
        }

The Angular API request (service):

followUser(followed_user, user_gd): Observable<any> {
    try {
      return this._http.post<any>(this._apiUrl + "FollowUser", { "user2_gd": followed_user, "user_gd": user_gd }, this.httpOptions);
    } catch (e) {
      console.log("POST error: ", e);
    }
  }

The component:

followUser(gd) {
    console.log(gd);
    this._userService.followUser(gd, localStorage.getItem("gd")).subscribe(
      res => {
        console.log(res);
      }
    )
  }

Everything seems to be functioning correctly, but I keep encountering the following error:

"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Guid' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'user2_gd', line 2, position 15."

Does anyone have a solution for this issue or has experienced the same problem before? Any help would be appreciated.

Answer №1

One way to improve your code is by defining a class with required fields and using it as a parameter in your FollowUser action:

public class FollowUserInfo
{ 
    public Guid userId { get; set; }
    public Guid userToFollowId { get; set; }
}

// Action to follow a user
[HttpPost]
public async Task<ActionResult<Guid>> FollowUser([FromBody] FollowUserInfo info)
{
   ... utilize the info object
}

You may find more insights on model binding in ASP.NET Core from Andrew Lock's helpful post.

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

Utilizing NgModelGroup nesting in various components for improved data management

Whenever I attempt to nest NgModelGroup inside another NgModelGroup, Angular seems to just ignore it. I'm currently utilizing Angular 12 and Template-driven Forms. Here is how my code appears: app.component.html <form #form="ngForm"> ...

Implement functionality in Angular to perform tasks when the page is reloaded

I need to perform certain actions in Angular when the page is reloaded, such as adding items to local storage before the page loads and removing items after the page has fully loaded. In other words, I want to execute some tasks both before and after refr ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

What are the best practices for utilizing generics effectively?

A series of interfaces has been defined: export interface FormData<T extends ControlData = any> { [type: string]: T; } export type FormResult<T extends FormData> = { [type in keyof T]: T[type]; }; export interface ControlData<T = any& ...

The error message "The type 'MouseEvent' is non-generic in TypeScript" popped up on the screen

Having created a custom button component, I encountered an issue when trying to handle the onClick event from outside the component. I specified the parameter type for the onClickCallback as MouseEvent<HTMLButtonElement, MouseEvent>, which is typical ...

What is the best way to display a block when a specific button is clicked?

I am looking to display this block only after clicking a button. Can someone help me achieve this in Angular? <div>Hello from some div block!</div> I have attempted the following: <button (click)="assign()">Button</button> <di ...

Primeng Growl component in Angular doesn't wrap text to the next line

Currently, I am facing an issue in Angular/Javascript where the text in growl is not wrapping using primeng 4.0.1. The problem arises when inserting a long file path into the growl, causing it to overflow from a single line. I am looking for a solution tha ...

Fetching information from the SharePoint platform

I am faced with the task of connecting to a hosted SharePoint website and extracting data from it to integrate into a C# application. Although the idea may seem complicated, I believe it would be most efficient to work with our existing SharePoint 2007 sit ...

Using Angular rxjs to efficiently make multiple API calls and merge their results in one response

After successfully making multiple calls to the same API with different payloads and merging the results into arrays of objects, I now need to mark each object in the result array for filtering purposes. For example, I want to add a property called api_id ...

Troubleshooting webpack's compatibility issues with @ngtools/webpack for efficient Angular lazy loading

Lazy module is loaded eagerly with no separate chunks created for lazy modules To replicate the issue, I have created a repository 1. Clone the repository from https://github.com/sameerthekhans/lazy-load-angular-webpack-temp.git 2. Run npm i 3. Start t ...

Looking for a way to retrieve all HTML tags that have a particular string in their attribute values with Html Agility Pack?

I am currently focused on extracting all HTML tags that have a specific string in their attribute values from the code provided below <meta name="DCSext.oo_market" content="en-us"> <a href="http://office.microsoft.com/en-us/support/" title="Find ...

Converting Getters into JSON

I am working with a sequelize model named User that has a getter field: public get isExternalUser(): boolean { return this.externalLogins.length > 0; } After fetching the User from the database, I noticed in the debugger that the isExternalUser prop ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

Oops! It seems like there has been an issue. The EnjoyHint is not

Encountered the following error message: https://i.stack.imgur.com/JL4l6.png The error in my code is within the line that initializes a new EnjoyHint object. Seeking assistance to resolve this issue. public initiate(stepName) { const steps = ...

Tips for running a dry default with Angular CLI

Query: Can dry-run be set as the default in a configuration? Purpose: Enabling dry-run by default simplifies the learning process by minimizing clean-up tasks if the command is not correct. This can encourage users to always perform a test run before exec ...

Utilizing ES6 JavaScript for Creating Static Methods and Angular 2 Services

During the development of an Angular 2 app involving multiple calculation services, I encountered some interesting questions: Is it beneficial to use static in an Angular service provided on the application level? Or is it unnecessary? How does a static ...

Analyzing a Specific DropDown Based on Condition

In my MVC project, I am working on a form that should be accessible based on certain conditions. The first view includes a dropdown list and a submit button. I want the value selected in the dropdown list to be passed and compared against a set condition. ...

Exploring the optimal procedures to asynchronously request an external API in Node.js using TypeScript

When handling a POST API request in a Node.js application built using TypeScript, it's necessary to make a call to an external API. This external API operates independently and must run in the background without impacting the response time. How can t ...

The compatibility issue of new controllers with React Templates in .NET Core 6

As I embark on my coding journey using ASP.NET Core 6 Web API and React starter template, I find myself at a crossroads despite hours of diligent research. The starter template comes with this controller: [ApiController] [Route("[controller]")] ...