蒋建雨
蒋建雨

Reputation: 375

How to call ajax only once in Angular and 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?

Upvotes: 4

Views: 1184

Answers (1)

siva636
siva636

Reputation: 16441

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.

Upvotes: 5

Related Questions