ngOnChanges(changes: SimpleChanges) {
if(changes.formName){
this.getFormConfigurations(this.formName);
}
getFormConfigurations(formName): void {
console.log('Inside form call..');
this.api.getForm(formName).subscribe((result)=>{
}
}
In API
getForm(name): Observable<any> {
console.log("Inside..API")
return this.http<>....
}
I am using this approach to call api on change in Angular , as output in console
Inside form call..
Inside..API
Inside form call..
Inside..API
Inside..API
Inside..API
As i see multiple API request on this how to avoid this type unnecessary API calls.
CodePudding user response:
ngOnChanges
will get called every time your formName
will be changed from the parent component resulting in multiple subscriptions. If you want to call your function only once, you can use attribute firstChange
of class SimpleChange
.
ngOnChanges(changes: SimpleChanges) {
if(changes.formName && changes.formName.isFirstChange()){
this.getFormConfigurations(this.formName);
}
CodePudding user response:
The ngOnChanges
lifecycle hook is invoked every time a change in the value of a data-bound property is found. Also, ngOnChanges
isn't where you should be subscribing to listen to the changes in your observable.
In order to limit the call to the API, you can do the following,
- If the said form is a
template-driven form
import { ViewChild } from '@angular/common'
@ViewChild('opportunityForm', { static: true }) ngForm: NgForm;
ngOnInit() {
this.changesInForm = this.ngForm.form.valueChanges.subscribe(x => {
// Invoke call to injectable
})
}
ngOnDestroy() {
this.changesInForm.unsubscribe();
}
<form #form="ngForm">
</form>
- If the said form is a
reactive form
form: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
});
this.onChanges();
}
onChanges(): void {
this.form.valueChanges.subscribe(value => {
// Invoke call to injectable
});
}