2016-10-04 10 views
0

私はAngular 2とフォームコンセプトを全く新しくしています。 POST API呼び出しにフォームデータをPOSTしようとしています。 http://localohot:8080/ **********角2:フォームを使用してPOST呼び出しを行う方法

コンポーネント:この

POSTのAPIのようにここで

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を行うと、彼らはいずれかが2角度

にそのフォームの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 

を送信している角度2で同じことをしようとしています

+1

公式の文書https://angular.io/docs/ts/latest/guide/server-communication.htmlをご覧ください。 – abhishekkannojia

+0

angular2のドキュメントは非常に優れており、非常に詳細です。ステップチュートリアル。私はまずそれを見るだろう。 – Igor

答えて

1

ここでは、Angular 2アプリでPOST呼び出しを行う方法を説明します。これは、フォームの設定方法の簡単な例を使用できるように思えるからです。ここには、角度2のドキュメントHow to Send Data to the Serverです。

Angular 2でAJAXリクエストを作成することに関するさらに高度なドキュメントについては、URLをご覧ください。私APP/

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

APP /フォーム成分/フォームをapp.module.tsで

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

このURLは角何のために非常に良いリファレンスです公式角度2ドキュメントサイトへのリンクである

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

} 

アプリ/フォームコンポーネント/ form.component.tsで2の開発者が望むかもしれない。

関連する問題