Home > Software design >  Angular - Send a request with multiple models to API
Angular - Send a request with multiple models to API

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:

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);
}

Update

.pipe(map((result: ProfileClientModel) => result))

As per Eliseo's feedback, the pipe() should be removed as map() is used to transform the data, while you try to transform the value into the same value, which is unnecessary.

  • Related