【问题标题】:Create a Contact form in Angular 2 / 4 that POSTS JSON to a specified API在 Angular 2 / 4 中创建一个将 JSON 发布到指定 API 的联系表单
【发布时间】:2017-04-15 15:27:00
【问题描述】:

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

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

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

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

【问题讨论】:

标签: angular aws-api-gateway


【解决方案1】:

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

1:我们抓取所有我们需要使用 Reactive Form 的 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:我们的 AppComponent 看起来像这样:

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

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

应用组件

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

【讨论】:

  • 首先,我去了你的 plunker 并使用我的 API 端点对其进行了修改,并在此处分叉了它(希望 - plunker 对我来说是新的):[link]plnkr.co/edit/ck7P2qFqFtp8sZJdwVVd?p=preview
  • 您能描述一下您的 API 输入吗
  • 但它不起作用,而且由于我缺乏经验,我无法排除故障。请你能给我任何指示如何最好地解决问题吗?我知道我必须更改表单字段 - 使用我在本文顶部提到的 JSON 文件测试 API
  • 对于我的 API 输入,我使用了你的 plunker 并将 API 端点更改为我自己的:我添加了一个测试名称和 cmets,然后按下“提交”
  • 如我所见,您需要包含 Authentication Token 才能向您的端点发送请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 2016-05-21
  • 1970-01-01
相关资源
最近更新 更多