在Angular 2/4中创建一个Contact表单,该表单将JSON发送到指定的API [英] Create a Contact form in Angular 2 / 4 that POSTS JSON to a specified API

查看:64
本文介绍了在Angular 2/4中创建一个Contact表单,该表单将JSON发送到指定的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create an Angular 2 / 4 project that has a 'Contact Us' form that creates data via JSON.stringify to then POST to my API that I have setup in AWS API Gateway. This uses Lambda and SES to email the details to me.

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

I am struggling learning Angular 2 / 4 and an working example of such type of form would be a terrific learning tool to amend and learn from.

我已经观看了许多Angular 2示例视频并阅读了教程,但是,我无法找到一种简单的形式来将JSON POST到API以进行跟踪/修改.

I have followed many Angular 2 example videos and read tutorials, but, I'm unable to find a simple form that POSTs JSON to an API to follow/amend.

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

Any help would be greatly appreciated folks! :)

推荐答案

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

Form in Angular is powerful and easy to use. Let's build a simple form with Reactive Form.

1::我们获取了所有需要使用Reactive Form的NgModule并使用Http调用AJAX:

1: We grab all NgModule we need to use Reactive Form and call AJAX with Http:

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 :我们的AppComponent如下所示:

2: And our AppComponent look like this:

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以创建我们的表单.

We inject FormBuilder class to AppComponent to create our form when Component Init.

然后我们使用Validators使用预构建的Validator函数-例如required.

And we use Validators to use pre-built Validator function - required for example.

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

In component template, we use some directive formGroup, formControlName to bind our form to template.

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

3: Now, we need a service to communicate with server:

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

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

Maybe in some case, you need include Header (Authorization token, for example), you need create header like this:

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

并发送带有标头的请求:

And send request with header:

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 :更新AppComponent和AppModule以使用服务

4: Update AppComponent and AppModule to use service

AppModule

// other import
import { PostService } from './post.service';

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

AppComponent

// 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发送您的数据.

When user click to button submit, onSubmit method will execute, then it'll call service method this.postService.saveContact to send your data.

您可以在此处使用Live Demo: https://plnkr.co/edit/GCYsGwreHi13FejcWDtE ?p =预览

You can play with Live Demo here: https://plnkr.co/edit/GCYsGwreHi13FejcWDtE?p=preview

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

这篇关于在Angular 2/4中创建一个Contact表单,该表单将JSON发送到指定的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆