Search code examples
angularangular-forms

how to prevent submiting a form after a second time in angular or how to submit a form only once


This is the function that submits my form

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");
    });
  }

the problem is that every time i pres enter or submit the form this function get called and the arrays are filled over and over again with data, and also that data overflows my html page


Solution

  • Add check before submitting logic and group api call 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]);
    });
    }
    

    // Then as optional you can also then disable button to prevent submitting. It just improves user experience

    <button [disabled]="isSubmitting">