Naman Jain
Naman Jain

Reputation: 411

Multiple APIs are called with (change) in angular

On selecting any date and hitting enter an API call should be made. And there's a x icon in the input on clicking it, it should call the API with date 01/01/12 Also this has feature like if you type 2/3 and hit enter it will automatically make it 02/03/20. The problem is if the input is empty and if I hit Enter same API calls are made thrice.

But the feature should be like if you select a date then without hitting Enter an API call should be made. I can't just use change function because if 2/3 is typed and Tab is pressed then it will not adjust the date automatically and also multiple API calls on hitting Enter. Is there a way to stop multiple API calls?

(change)="startDate($event)" (keydown.enter)="CallAPI($event)"

    startDate(event) {
        if (event.target.value == '' || event.target.value == null)
            this.cutoverFilterApi(event)
    }
    CallAPI(event) {
        let data = event.target.value;
        if (data != '' && data != null && data != "NaN/NaN/NaN") {
            data = data;
        } else {
            data = "01/01/12";
        }
        this.httpService.getData('PATH' + data).subscribe((response: any) => {
            this.dateChangeData = response.results;
            this.rowData = response.results;
            this.gridApi.setRowData(this.rowData);
        });
    }

enter image description here

Upvotes: 1

Views: 1023

Answers (2)

Mahipal Choudhary
Mahipal Choudhary

Reputation: 405

You can use this

(dateInput)="addEvent('input', $event)" (dateChange)="addEvent('change', $event)"

instead of

(change)="startDate($event)" (keydown.enter)="CallAPI($event)"

I have an example of angular material datepicker, which will make your code easier.

Reference link

I hope it is helpful for you. :)

Upvotes: 0

cabesuon
cabesuon

Reputation: 5270

You could keep the last valid value and avoid request if it is the same.

Something like this,

lastDate = null; // <- variable to keep last value
CallAPI(event) {
    let data = event.target.value;
    if (data != '' && data != null && data != "NaN/NaN/NaN") {
        data = data;
    } else {
        data = "01/01/12";
    }
    // check if data is not the same as last request
    if (this.lastDate === data) {
        return;
    }
    this.lastDate = data; // <- update new request date
    this.httpService.getData('PATH' + data).subscribe((response: any) => {
        this.dateChangeData = response.results;
        this.rowData = response.results;
        this.gridApi.setRowData(this.rowData);
    });
}

Upvotes: 1

Related Questions