0
私は 'angular2 +'アプリケーションでformspree.ioを使用して連絡先フォームを実装しようとしています。私のコンポーネントからhttpリクエストを直接処理したくないので、私はこの仕事をするためのコンタクトサービスを作成しました。 残念ながら私の要求が適切に掲載されていないようだ。Angular2 + Formspree。不正なリクエスト400
状態:400(不正な要求){ "エラー": "空のフォームを送信することはできません"}
ここに私のコード:
をcontact.service.ts
import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions, URLSearchParams} from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ContactService {
constructor(private http: Http) {
}
postEmail(name: String, email: String, message: String): Observable<string>{
let headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
});
let options = new RequestOptions({ headers: headers });
let url = "http://formspree.io/[email protected]";
let data = {
name: name,
email: email,
message: message
}
return this.http.post(url, data, options)
.map(response => {
console.log('email sent', response);
return response;
})
.catch(this.handleError);
}
private handleError(err){
//error handling
}
}
contact.component.ts
import { Component} from '@angular/core';
import { ContactService } from './contact.service';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { Contact } from './contact.interface';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
emailForm: FormGroup;
messageSentSuccess: boolean;
messageSentError: boolean;
events: any[]=[];
constructor(
private service: ContactService,
private _fb: FormBuilder
) {
this.emailForm = this._fb.group({
'email': [null, Validators.compose([Validators.required])],
'name': [null, Validators.required ],
'message': [null, Validators.compose([Validators.required, Validators.minLength(10)])]
});
}
onSubmit(form: any) {
this.service.postEmail(form.value.name.toString(),form.value.email.toString(),form.value.message.toString())
.map(res => res)
.subscribe(
res => {},
error => {
this.messageSentError = true;
this.emailForm.reset();
setTimeout(()=>{this.messageSentError=false},3000);
},
() => {
this.messageSentSuccess=true;
setTimeout(()=> { this.messageSentSuccess=false },3000);
}
);
}
}
フォームデータがコンソールで印刷されているかどうかを確認できます –
送信データがnullに評価されています –
フォームデータが正しく送信されました。つまり、変数名、コンソールで) – Ugo