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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With