在 Angular 2 / 4 中创建一个联系人表单,将 JSON 发布到指定的 API



我正在尝试创建一个具有"联系我们"表单的 Angular 2/4 项目,该项目通过 JSON.stringify 创建数据,然后发布到我在 AWS API Gateway 中设置的 API。 这使用 Lambda 和 SES 通过电子邮件将详细信息发送给我。

我正在努力学习 Angular 2/4,这种形式的工作示例将是一个很好的学习工具,可以修改和学习。

我已经关注了许多 Angular 2 示例视频并阅读了教程,但是,我找不到一个简单的表单将 JSON 发布到 API 以遵循/修改。

任何帮助将不胜感激! :)

Angular 中的表单功能强大且易于使用。 让我们用反应式表单构建一个简单的表单。

1:我们获取所有需要使用响应式表单的 NgModule,并使用 Http 调用 AJAX:

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [ 
BrowserModule, 
HttpModule, // for http request
ReactiveFormsModule // for form system
],
declarations: [ AppComponent ],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule {}

2:我们的应用组件看起来像这样:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FromGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
<h2>Contact Form</h2>
<form [formGroup]="frmContact" (ngSubmit)="onSubmit()" novalidate>
<div>
<label>
Name:
<input type="text" formControlName="name">
</label>
</div>
<div>
<label>
Comment:
<textarea formControlName="content"></textarea>
</label>
</div>
<button [disabled]="frmContact.invalid">Submit</button>
</form>
<div *ngIf="res">
Response:
<pre>{{ res | json }}</pre>
</div>
`,
})
export class AppComponent implements OnInit, OnDestroy {
frmContact: FormGroup;
private _sub;
res: any;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.frmContact = this.fb.group({
name: ['', Validators.required],
content: ['', Validators.required]
});
}
onSubmit() {
let formValue = this.frmContact.value;
// cool stuff to transform form value
// call AJAX
}
ngOnDestroy() {
// clean subscription when component destroy
if (this._sub) {
this._sub.unsubscribe();
}
}
}

我们将 FormBuilder 类注入到 AppComponent 中,以便在组件初始化时创建表单。

我们使用Validators来使用预构建的验证器函数 - 例如required

在组件模板中,我们使用一些指令formGroupformControlName将表单绑定到模板。

3:现在,我们需要一个服务来与服务器通信:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class PostService {
private API_ENDPOINT = '//jsonplaceholder.typicode.com/posts'; //replace with your API ENDPOINT
constructor(private _http: Http) {}
saveContact(contact: any) {
return this._http.post(this.API_ENDPOINT, contact)
.map(res => res.json());
}
}

也许在某些情况下,您需要包含标头(例如授权令牌),您需要像这样创建标头:

let headers = new Headers({ 'Content-Type': 'application/json' }); // create new Headers object with header Content-Type is application/json.
headers.append('Authorization', 'Bearer ' + your_token); //JWT token
let options = new RequestOptions({ headers: headers });

并发送带有标头的请求:

saveContact(contact: any) {
let headers = new Headers({ 'Content-Type': 'application/json' }); // create new Headers object with header Content-Type is application/json.
headers.append('Authorization', 'Bearer ' + your_token); //JWT token
let options = new RequestOptions({ headers: headers });
return this._http.post(this.API_ENDPOINT, contact, options)
.map(res => res.json());
}

4:更新应用程序组件和应用程序模块以使用服务

应用模块

// other import
import { PostService } from './post.service';
@NgModule({
imports: [ 
//...
],
declarations: [ AppComponent ],
providers: [ PostService ], // declare our service into this array
bootstrap: [ AppComponent ]
})
export class AppModule {}

应用组件

// other import
import { PostService } from './post.service';
@Component({
//...
})
export class AppComponent implements OnInit, OnDestroy {
frmContact: FormGroup;
private _sub;
res: any;
constructor(private fb: FormBuilder, private postService: PostService) {}
ngOnInit() {
//...
}
onSubmit() {
let formValue = this.frmContact.value;
// cool stuff to transform form value
// call AJAX
this._sub = this.postService.saveContact(formValue)
.subscribe(data => {
console.log(data)
this.res = data;
});
}
ngOnDestroy() {
// clean subscription when component destroy
if (this._sub) {
this._sub.unsubscribe();
}
}
}

当用户单击按钮提交时,onSubmit方法将执行,然后它将调用服务方法this.postService.saveContact来发送数据。

您可以在此处玩现场演示:https://plnkr.co/edit/GCYsGwreHi13FejcWDtE?p=preview

文档: https://angular.io/docs/ts/latest/guide/server-communication.html

最新更新