Home > other >  Send multiple models in request from angular service to c# method
Send multiple models in request from angular service to c# method

Time:12-31

I'm new in Angular, and I'm currently into a big project where many people work, so the project is based on Angular for the front end and C# for the back end.

So, the project has some services that call the backend service as:

front:

   public editProfileClient(profileClient) {
        return this.http
          .post(this.url   '/editProfileClient', profileClient)
          .pipe(map((result: ProfileClientModel) => result));
      }

back:

 public async Task<ActionResult> EditProfileClient(ProfileClient profileClient)
        {
          //irrelevant code here
          return Ok(model);
        }

This is working well, but now I want to send a new model called Salary to that request, so I changed the back as:

 public async Task<ActionResult> EditProfileClient(ProfileClient profileClient, Salary salary)

but I have no idea how I can send it on the front, so I receive it, but I cannot call it:

  public editProfileClient(profileClient, salary) {
    return this.http
      .post(this.url   '/editProfileClient', profileClient, salary)
      .pipe(map((result: ProfileClientModel) => result));
  }

If I try to do that, the method returns an error:

Argument of type 'OperatorFunction<ProfileClientModel, ProfileClientModel>' is not assignable to parameter of type 'OperatorFunction<ArrayBuffer, ProfileClientModel>'.

How can I achieve that?

CodePudding user response:

  1. For the API part, combine both parameters into a single object as below:
public async Task<ActionResult> EditProfileClient(EditProfileClientInputModel input)
public class EditProfileClientInputModel
{
    public ProfileClient ProfileClient { get; set; }
    public Salary Salary { get; set; }
}
  1. For the front-end part:

    2.1. Combine both profileClient and salary parameters into a single object and pass it.

    2.2. As your API returns the response of ProfileClientModel type, you should also specify the generic type: post<T>()

public editProfileClient(profileClient, salary) {
  let input = {
    profileClient: profileClient,
    salary: salary
  };

  return this.http
    .post<ProfileClientModel>(this.url   '/editProfileClient', input)
    .pipe(map((result: ProfileClientModel) => result));
}
  • Related