Search code examples
httppostangularform-parameter

how to send post with FormParams using Angular2


client:

I do post in angular2 like this:

doSelectMessagesAttributesUrl2(pushRequest : PushRequest) {
    console.info("sending post request");

    let headers = new Headers({
        'Content-Type': 'application/json'});

    return this.http
        .post(this.selectMessagesAttributesUrl, JSON.stringify(pushRequest), {headers: headers})
        .map(res => res.json().data)
        .subscribe(
            data => { },
            err => {  }
        );
}

How should i change the request to call the server with FormParam?

server:

 @Path("/FeatureGetQueueData")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public String runFeatureGetQueueData(@FormParam("queue") MyString paramQueue) throws Exception {

        if (!SupporToolAlert.validateEnvironment(SupporToolConfig.ROW)) {
            return SupporToolAlert.invalidEnvironment();
        }

        String queue = PushQueueConfig.conf().QUEUE.get(paramQueue.value);

Solution

  • Did you combine your form with any model ??

    In documentation you can search nice example: right here

    But if u don't want to create class for your form, u can do something like this:

    add each element from form to object, and send this object via http.

    something like this:

    form.html

    <form>
     <div class="form-group">
                <label for="status"> Status: </label>
                <input id='status' type="text" class="form-control" [ngModel]="formModel.operatorStatus" (ngModelChange)="changeFormModel('status', $event)" >
              </div>
    </form>
    

    now in you component, you need init empty object to contains data from model and implement changeFormModel:

    component.ts

    private formModel: any = {};
    private changeFormModel(model, event) {
        this.formModel[model] = event;
    }
    

    now in your http request u can send, formModel, remember to stringify it ;)

    Thats not is a perfect solution, but works like charm for me, but in near future i will implement a solution from documentation.

    I hope it helped you ;)