Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

Angular 2 : How to make POST call using form

I am completely new to Angular 2 and form concept. I am trying to POST form data to a POST API call. like this

POST API : http://localohot:8080/**********

Component :

user: any = {
    id: null,
    gender: null,
    mstatus: null,
    birthdate: null,
    bloodgroup: null
}

userName: any = {
    id: null,
    personId: null,
    displayName: '',
    prefix: null,
    givenName: null
}

userAddressJSON: any = {
    id: null,
    personId: null,
    address1: null,
    address2: null,
    cityVillage: null
}

var form = new FormData();
form.append('userid', new Blob(['' + uid], { type: 'application/json' }));
form.append('user', new Blob([JSON.stringify(this.user)], { type: 'application/json' }));
form.append('userName', new Blob([JSON.stringify(this.userName)], { type: 'application/json' }));
form.append('userAddress', new Blob([JSON.stringify(this.userAddressJSON)], { type: 'application/json' }));

Here, I don't know how to make API call. In our old application they used form data POST in jQuery. Now I am trying to do the same in Angular 2. When I do the form POST in old application they are sending like this

------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userid"; filename = "blob"
Content - Type: application / json


------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "user"; filename = "blob"
Content - Type: application / json


------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userName"; filename = "blob"
Content - Type: application / json


------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userAddress"; filename = "blob"
Content - Type: application / json

Can any one help me how to do that form POST in Angular 2.

Upvotes: 0

Views: 1579

Answers (1)

Logan H
Logan H

Reputation: 3423

Here is how I currently make a POST call in my Angular 2 app, because it sounds like you could use a simple example of how to setup a form. Here is the Angular 2 documentation on How to Send Data to the Server.

For even more high level documentation on making AJAX requests in Angular 2 visit this URL.

in my app/app.module.ts

...
import { HttpModule }     from '@angular/http';
...

@NgModule({
    imports: [
        ...
        HttpModule
        ...
    ],
    declarations: [
        ...
    ],
    providers: [ ... ],
    bootstrap: [AppComponent],
})
export class AppModule { }

app/system-setup/system-setup.ts

export class SystemSetup {
    system_setup_id: number;
    name: string;
    counter: number;
}

app/form-component/form.component.html (Notice the [(ngModel)], that is what binds the property of the object to the html input element)

<form class="form" (ngSubmit)="saveEdits()" #editSystemSetupForm="ngForm">
<div class="row">

  <div class="col-md-6">

    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" class="form-control" id="theName" name="name" [(ngModel)]="selectedItem.name" #itemsName="ngModel" required minlength="3"/>
      <div [hidden]="itemsName.valid || itemsName.pristine" class="alert alert-danger">Name is required! Min length of 3.</div>
    </div>
  </div>

  <div class="col-md-6">
    <div class="form-group">
      <label for="">Counter</label>
      <input type="number" step=0.01 class="form-control" name="counter" [(ngModel)]="selectedItem.counter" />
    </div>
  </div>

</div>

<div class="row">
  <div class="col-md-4 col-md-offset-8">
    <button type="submit" class="btn btn-success" style="float: right; margin-left: 15px;" [disabled]="!editISystemSetupForm.form.valid" >Save</button>
    <button type="button" class="btn btn-danger" style="float: right;" (click)="cancelEdits()">Cancel</button>
  </div>
</div>
</form>

in my app/form-component/form.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Headers, RequestOptions, Http, Response } from '@angular/http';
import { SystemSetup } from '../system-setup/system-setup';

@Component({
  selector: 'app-setup-form',
  templateUrl: 'setup-form.component.html',
  styleUrls: ['setup-form.component.css']
})
export class SetupFormComponent implements OnInit {
    @Input()    selectedItem: SystemSetup; // The object to be edited
    @Output()   finishedEditing = new EventEmitter<number>(); // When the POST is done send to the parent component the new id

    // Inject the Http service into our component
    constructor(private _http: Http) { }

    // User is finished editing POST the object to the server to be saved
    saveEdits(): void {
        let body = JSON.stringify( this.selectedItem );
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this._http.post('http://localhost:8080/**********', body, options)
               .map(this.extractData)
               .do(
                  data => {
                     this.finishedEditing.emit(data.system_setup_id); // Send the parent component the id if the selectedItem
               })
               .toPromise()
               .catch(this.handleError);
    }


    /**
     * Gets the data out of the package from the AJAX call.
     * @param  {Response} res - AJAX response
     * @returns SystemSetup - A json of the returned data
     */
    extractData(res: Response): SystemSetup {
        let body = res.json();
        if (body === 'failed') {
          body = {};
        }
        return body || {};
    }

    /**
     * Handles the AJAX error if the call failed or exited with exception. Print out the error message.
     * @param  {any} error - An error json object with data about the error on it
     * @returns Promise - A promise with the error message in it
     */
    private handleError(error: any): Promise<void> {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Promise.reject(errMsg);
    }

}

This URL is the link to the official Angular 2 documentation site, which is a very good reference for anything an Angular 2 developer could want.

Upvotes: 1

Related Questions