1
votes

I am posting request using httpClient like:

I have imported HttpClientModule in app.module.js for http get and post request.

const httpOptionsWithCookie = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded'}), withCredentials: true };

this.baseUrl ("link of API")

postArguments is an object like " {name:"xyz",company:"abc"}"

this.http.post(this.baseUrl, postArguments, httpOptionsWithCookie);

I am using angular5 in front end and spring mvc at back end I am new in angular5.

API side code :

**spring mvc imports

             @RestController
             @RequestMapping(value = "/api/leavePeriod")
             public class LeavePeriodControllerApi {
     private static LogHelper logHelper = LogHelper
        .getInstance(LeaveApplicationControllerApi.class);

    @Autowired
    HttpSession session;

    @Autowired
    Environment env;

    @Autowired
    ILeavePeriodService service;

    @Autowired
    ISecurityCommonService securityCommonService;

    @Autowired
    ILeaveCategoryService leaveCategoryService;

    @Autowired
    ICompanyService companyService;

    @Autowired
    LeavePeriodValidator leavePeriodValidator;

  private User user = new User();
    private String LOGINUSER = "";

 @RequestMapping(value = "/viewLeavePeriod", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object>  viewLeavePeriod( @ModelAttribute LeavePeriodForm form,HttpServletRequest request,@RequestParam(value ="companyId" ,required = false)
    String companyId, @RequestParam(value ="leaveCategoryId", required = false)
    String leaveCategoryId )throws HRAlignBaseException {
     user = (User) session.getAttribute("user");
        LOGINUSER = "LoginUser " + user.getEmpName() + " loginuser empCode "
                + user.getEmpCode();    
        Map<String, Object> returnMap = new HashMap<String, Object>();

     try{
         if(companyId!= null && companyId!="")
         {
             form.setCompanyId(Integer.parseInt(companyId)); 
         }
         if(leaveCategoryId!= null && leaveCategoryId!="")
         {
             form.setLeaveCategoryId(Integer.parseInt(leaveCategoryId));
         }

         returnMap = service.view(form);
         returnMap.put("periodList", form.getLeavePeriodVoList());
         returnMap.put("comId", form.getCompanyId());
         returnMap.put("leaveCatId", form.getLeaveCategoryId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        logHelper
        .info("################"
                + LOGINUSER
                + "############# END Enter LeavePeriodController viewLeavePeriod");
        return returnMap;
    }

}

the same http post request work in angularjs but it's not working in angular5.

Also when doing the same http post from ARC, it's working fine but not working for angular5

1

1 Answers

1
votes

for 'Content-Type': 'application/x-www-form-urlencoded' form data should be sent like "menuId=5&buttonRights=adfasdfad&abc=aasdfasdfd" and not in json format so this feature available in angularjs(ngResource)but not in angular 5(HttpClient). this is a standard way to post data. Below code is for simple object.

   import { URLSearchParams } from "@angular/http"


   testRequest() {
   let data = new URLSearchParams();
    data.append('username', username);
    data.append('password', password);

   this.http
    .post('/api', data)
    .subscribe(data => {
        alert('ok');
     }, error => {
      console.log(error.json());
     });
     }

if you want to post object or nested object ,you have to manually convert the object to query string using below code.

       jsonTransformRequest (data) {
          var param = function (obj) {
           var query = '';
        var name, value, fullSubName, subValue, innerObj, i;

     for (name in obj) {
      value = obj[name];

      if (value instanceof Array) {
          for (i = 0; i < value.length; ++i) {
              subValue = value[i];
              fullSubName = name + '[' + i + ']';
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
          }
      } else if (value instanceof Object) {
          for (let subName in value) {
              subValue = value[subName];
              fullSubName = name + '.' + subName;
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
          }
      } else if (value !== undefined && value !== null) {
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
  }
  return query.length ? query.substr(0, query.length - 1) : query;
      };
       var ret =  (data != null && typeof data === 'object') ? param(data) : 
     data;
      return ret;
     };