Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ajax only once in Angular and Rxjs?

Tags:

angular

rxjs

There are code:

<button (click)="getData()">click<button>

getData(){
  this.http.get('/data.json').subscribe(data => consloe.log(data));
}

or use post

 <button (click)="setData(data)">click<button>
    getData(){
      this.http.post('/data',{data}).subscribe(res =>consloe.log(res));
    }

When I click button many time continuously, it will send many time http requests. How I avoid it?

like image 463
蒋建雨 Avatar asked Oct 27 '25 03:10

蒋建雨


1 Answers

Get the data once, for example in ngOnInit() method, and shareReplay(1) it to cache the result.

ngOnInit(){
this.myData =  this.http.get('/data.json').shareReplay(1);
}

Now subscribe the resulted observable in your button action method:

 getData(){
     this.myData.subscribe(data => consloe.log(data));
    }

The above technique will connect the server only once no matter how many times you click the button.

like image 194
siva636 Avatar answered Oct 28 '25 17:10

siva636