【发布时间】:2018-10-04 13:38:47
【问题描述】:
我有一些字段的响应式表单:
this.pointForm = new FormGroup({
X_WGS84: new FormControl(null, Validators.required),
Y_WGS84: new FormControl(null, Validators.required),
country: new FormControl(null),
state: new FormControl(null),
... etc
在 onSubmit 方法中,我将表单中的字段分配给 Point 类:
export class Point {
X_WGS84: number;
Y_WGS84: number;
country?: string;
state?: string;
... etc
但我不知道,如何在同一个请求中同时发送表单数据和图像。
onSubmit() {
if (this.pointForm.valid) {
Object.keys(this.pointForm.value).forEach(key => {
this.point[key] = this.pointForm.value[key] === '' ? null : this.pointForm.value[key];
});
this.httpService.addPoint(this.point, this.fileToUpload).subscribe(
point => {
this.router.navigate(['/home']);
},
error => {
console.log(error.statusText);
});
}
}
我做了类似的事情:
constructor(private http: HttpClient) {}
addPoint(point: Point, fileToUpload: File): Observable<Point> {
const formData: FormData = new FormData();
formData.append('image', fileToUpload, fileToUpload.name);
formData.append('Point', point);
return this.http.post<Point>('http://localhost:8000/point/new', formData);
}
但是:
- 我认为我不应该这样做
- 我认为,如果出现我不明白的错误:
发送此类请求的正确方法是什么?
【问题讨论】:
标签: file post angular5 httpclient angular-reactive-forms