hamna mariyam
hamna mariyam

Reputation: 13

How to prevent two API calls in Angular?

In Angular, how to prevent two API calls?
I call a function two times in ngOninit, one should only call when id changes from URL parameter. While loading the page for the first time itself both functions get invoked.

ngOnInit() {
  this.getCategoryList();
  this.route.params.subscribe(params => {
    console.log("categoryChange");
    this.categoryId = params['cat'] || '';
    if (this.categoryId) {
      this.getCategoryList();
    }
  });
}

Upvotes: 1

Views: 1487

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can use distinct() to filter distict values.

this.route.params.pipe(map(params => params['cat']), distinct())
.subscribe(cat => {
    console.log(cat);
});

Or use debounce() to avoid frequent calls

this.route.params.pipe(map(params => params['cat']), debounceTime(100))
.subscribe(cat => {
    console.log(cat);
});

Or you can just compare the previous value and avoid calling API if it's the same.
this.route.params.subscribe(params => {
  console.log("categoryChange");
  const categoryId = params['cat'] || '';
  if (this.categoryId !== categoryId && categoryId) {
    this.categoryId = categoryId;
    this.getCategoryList();
  }
});

Upvotes: 3

navnath
navnath

Reputation: 3714

If route param is available it will assign categoryId else null will be used. You can assign any default value instead of null if cat param is unavailable.

This makes sure you will have only one API call if route param is available or not.

Remove this.getCategoryList() call onOnit. So final code will be

import { map } from 'rxjs/operators';

ngOnInit(): void {
    this.route.params.pipe(
      map(param => param['cat'] || null)
    ).subscribe(categoryId => {
      this.categoryId = categoryId;
      this.getCategoryList();
    });
  }

Upvotes: 0

Related Questions