import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
addProfile(formValue) {
const formData = new FormData();
for (const name of Object.keys(formValue)) {
if (typeof formValue[name] === 'object') {
if (name === 'education') {
const eduList = formValue[name];
for (const field of Object.keys(eduList)) {
if (typeof eduList[field].school === 'string') {
const clgname = eduList[field].school;
this.addNewField(clgname, 'college').toPromise().then((data: any) => {
eduList[field].school = {college_id: data.id, collegename: clgname};
console.log(eduList[field].school, name);
formData.append(name, JSON.stringify(formValue[name]));
});
} else {
console.log('enter');
formData.append(name, JSON.stringify(formValue[name]));
}
}
} else if (name === 'experience') {
const compList = formValue[name];
for (const field of Object.keys(compList)) {
if (typeof compList[field].company === 'string' && compList[field].company.trim() !== '') {
const compname = compList[field].company;
compList[field].company = {companyname: compname, company_id: null};
}
}
formData.append(name, JSON.stringify(formValue[name]));
} else if (name === 'course') {
const corsList = formValue[name];
for (const field of Object.keys(corsList)) {
if (typeof corsList[field].coursename === 'string' && corsList[field].coursename.trim() !== '') {
const corsname = corsList[field].coursename;
corsList[field].coursename = {coursename: corsname, course_id: null};
}
}
formData.append(name, JSON.stringify(formValue[name]));
} else {
formData.append(name, JSON.stringify(formValue[name]));
}
} else {
formData.append(name, formValue[name]);
}
}
return this.http.post('/api/user/addProfile.php', formData);
}
addNewField(fieldName, dbName) {
const formData = new FormData();
formData.append('fieldName', fieldName);
formData.append('dbName', dbName);
return this.http.post('/api/user/addNewField.php', formData);
}
}
在此http请求完成之前提交此函数调用addProfile()
return this.http.post('/api/user/addProfile.php', formData);
时,如何在formData
函数中管理多个http requset
this.addNewField(clgname, 'college').toPromise().then((data: any) => {
eduList[field].school = {college_id: data.id, collegename: clgname};
console.log(eduList[field].school, name);
formData.append(name, JSON.stringify(formValue[name]));
});
如何在addNewFieled()
完成该过程之前等待,然后将其所有formData附加到我的上一个http请求中,从而可以在角度6中等待直到上一个请求完成。
答案 0 :(得分:0)
您需要等待addNewField()
承诺完成后才能调用下一个HTTP请求(或对该请求进行其他工作)
最简单的方法是使用Promise.all
并执行类似的操作
formData = new FormData()
promises = [];
// your business
promises.append(addNewField().toPromise().then(/* your old code*/))
return Promise.all(promises).then(this.http.post('/api/user/addProfile.php', formData))