如何防止在 angular 中第二次提交表单或如何仅提交一次表单
how to prevent submiting a form after a second time in angular or how to submit a form only once
这是提交我的表单的函数
onSubmit(form: NgForm) {
this.cityName = form.value.city;
this.weatherService.getCurrentWeather(form.value.city).subscribe((res) => {
this.searchedLocationData = res;
});
this.weatherService.getForecast(form.value.city).subscribe((res: any) => {
for (let i = 0; i < res.list.length; i += 8) {
this.searchedLocationForecast.push(res.list[i]);
}
console.log(this.searchedLocationForecast, "forecast");
});
}
问题是每次我按下输入或提交表单时都会调用此函数,并且数组会一遍又一遍地填充数据,而且数据会溢出我的 html 页面
在提交逻辑前添加检查并群api调用like
public onSubmit(form: NgForm): void {
if (this.isSubmitting) {return; }
this.isSubmiting = true;
this.cityName = form.value.city;
combineLatest(
this.weatherService.getCurrentWeather(this.cityName),
this.weatherService.getForecast(this.cityName)
)
.pipe(
finalize(() => this.isSubmitting = false)
)
.subscribe([getCurrentWeatherRes,getForecastRes]) => {
// some stuff
this.searchedLocationData = getCurrentWeatherRes;
this.searchedLocationForecast.push(getForecastRes.list[i]);
});
}
// 然后作为可选,您还可以禁用按钮以防止提交。它只是改善了用户体验
<button [disabled]="isSubmitting">
这是提交我的表单的函数
onSubmit(form: NgForm) {
this.cityName = form.value.city;
this.weatherService.getCurrentWeather(form.value.city).subscribe((res) => {
this.searchedLocationData = res;
});
this.weatherService.getForecast(form.value.city).subscribe((res: any) => {
for (let i = 0; i < res.list.length; i += 8) {
this.searchedLocationForecast.push(res.list[i]);
}
console.log(this.searchedLocationForecast, "forecast");
});
}
问题是每次我按下输入或提交表单时都会调用此函数,并且数组会一遍又一遍地填充数据,而且数据会溢出我的 html 页面
在提交逻辑前添加检查并群api调用like
public onSubmit(form: NgForm): void {
if (this.isSubmitting) {return; }
this.isSubmiting = true;
this.cityName = form.value.city;
combineLatest(
this.weatherService.getCurrentWeather(this.cityName),
this.weatherService.getForecast(this.cityName)
)
.pipe(
finalize(() => this.isSubmitting = false)
)
.subscribe([getCurrentWeatherRes,getForecastRes]) => {
// some stuff
this.searchedLocationData = getCurrentWeatherRes;
this.searchedLocationForecast.push(getForecastRes.list[i]);
});
}
// 然后作为可选,您还可以禁用按钮以防止提交。它只是改善了用户体验
<button [disabled]="isSubmitting">