2016-10-04 52 views
0

我是完全新的角2和形式的概念。我正在嘗試將POST數據發送到POST API調用。這樣Angular 2:如何使用表格

POST APIhttp://localohot:8080/ **********

組件:

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

在這裏,我不知道如何使API調用。 在我們的舊應用程序中,他們使用jQuery中的表單數據POST。現在,我想我做舊的應用程序的形式POST他們發送這樣

------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 

任何一個可以幫助我如何做,表單POST在角2

做同樣的角2
+1

我建議你看看官方文檔https://angular.io/docs/ts/latest/guide/server-communication.html – abhishekkannojia

+0

angular2的文檔非常好,非常詳細,它也有一個步驟一步教程。我會先看看。 – Igor

回答

1

以下是我目前在我的Angular 2應用程序中進行POST調用的方式,因爲它聽起來像您可以使用一個簡單的如何設置表單的示例。這裏是關於How to Send Data to the Server的Angular 2文檔。

有關在Angular 2中製作AJAX請求的更高級別文檔,請訪問此URL

在我應用程序/ app.module.ts

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

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

應用程序/系統設置/系統setup.ts

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

應用程序/形式組分/形式.component.html(注意[(ngModel)],即將對象的屬性綁定到html輸入元素)

<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> 

在我應用程序/表單組件/ 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); 
    } 

} 

URL是鏈接到官方角2文檔的網站,這是任何一個角度很好的借鑑意義2開發人員可能需要。