Home > Net >  How to map request parameter fields in angular-httpclient?
How to map request parameter fields in angular-httpclient?

Time:11-12

I have an angular project that has a user registration form that creates the following Registration object which is then passed into a register service. However, the service request parameters are underscore_cased. How can I remap firstName and lastName to first_name and last_name before I send the http request?

export class Registration {
  email: string;
  firstName: string;
  lastName: string;
}

register(registration: Registration) {
    console.log('Registration submitted', registration);
    return this.http.post(`${environment.authUrl}/auth/register`, registration).pipe(
       catchError(err => {
            console.log('Handling error locally and rethrowing it...', err);
            return throwError(err);
       })
    );
}

CodePudding user response:

You can create a new object with desired key name and initialize that newly created object with registeration object's value.

register(registration: Registration) {
  const registerUserObject = {
    'first_name' : registration.firstName,
    'last_name' : registration.lastName,
    'email' : registration.email
  } ;
   
  return this.http.post(`${environment.authUrl}/auth/register`, registerUserObject).pipe(...);
}

CodePudding user response:

You can set them by using pure Javascript:

register(registration: Registration) {
    let body = new URLSearchParams();
    
    Object.entries(registration).forEach(
      ([key, value]) => {
        body.set(key, value)
      }
    );

   return this.http.post(`${environment.authUrl}/auth/register`, body.toString())...
}
  • Related