简体   繁体   English

如何在 angular-httpclient 中映射请求参数字段?

[英]How to map request parameter fields in angular-httpclient?

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.我有一个 angular 项目,它有一个用户注册表单,它创建以下 Registration 对象,然后将其传递到注册服务中。 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?如何在发送 http 请求之前将 firstName 和 lastName 重新映射到 first_name 和 last_name?

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

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

You can set them by using pure Javascript:您可以使用纯 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())...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM