简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM