Aayushi Gupta
Aayushi Gupta

Reputation: 367

I am getting multiple calls from angular to the Post API in Node

I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help. component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}

I want the call to be sent only once, not twice

Upvotes: 1

Views: 121

Answers (4)

Micah Bolen
Micah Bolen

Reputation: 151

Try this:

// Somewhere on init
let postRequestCount = 0;

// More stuff …

// Just before doing the POST request inside the `selectCountry` method
if(postRequestCount < 1) {
    http.post(); // TODO : Replace with the actual `post` method
} 
postRequestCount++;

Upvotes: 0

Jayoti Parkash
Jayoti Parkash

Reputation: 878

Change your service method like:

add interface:

export interface Country{
  id: number;
  name: string;
}

Change your method:

getCountries(): Observable<Country> {
    return this.httpClient
      .get('pass api url here')
      .pipe(
        map((body: any) => body),
        catchError(error => of(error))
      );
  }

In your component:

ngOnInit() {
    this.countryService.getCountries().subscribe(
          (result: Countries) => {
            this.countries = result;
          },
          err => {
            log.debug('get countries error', err);
          }
        );
      }
}

Upvotes: 0

Need all your code if you can do a stackblitz, and like Mateusz said its better to handle state with ngrx if you dont want to call twice to backend or a simple approach its something like this https://stackblitz.com/edit/angular-biv6cw.

Upvotes: 0

Mateusz Klimentowicz
Mateusz Klimentowicz

Reputation: 709

Btw. - Please consider adding the NGRX lib in your app.

An angular-service is considered as a data holder. So make there an instance variable. It could look like:

export class Service{
  private countries;
  ...
  public getCountries(){
     return this.countries;
  }

  public loadCountries(){
     this.http.get("url").subscribe(countries => this.countries = countries);
  }
}

Then in your component class, you just get the countries.

export class Component{
  public coutries;
  ...
  public ngOnInit(){
    this.countryService.getCountries(countries => this.countries=coutries);
  }
 }

And last but not least - load the countries in your AppComponent.

export class AppComponent{
  ...
  public ngOnInit(){
     this.countryService.loadCountries();
  }
}

Upvotes: 1

Related Questions