So i have this Component of a from with an @Output
event that trigger on submit, as follows:
@Component({
selector: 'some-component',
templateUrl: './SomeComponent.html'
})
export class SomeComponent{
@Input() data: any;
@Output() onSubmit: EventEmitter<void> = new EventEmitter<void>();
constructor(private someService: SomeService) {}
submitForm(): void{
this.someService.updateBackend(this.data, ()=>{
this.onSubmit.emit();
});
}
}
I'm using an ngFor
to create multiple elements of this Component :
<template let-data ngFor [ngForOf]="dataCollection">
<some-component [data]="data" (onSubmit)="doSomthing()"></some-component>
</template>
The last missing part is the service used on submitting:
@Injectable()
export class SomeService{
constructor() {}
updateBackend(data: any, callback: () => void): void{
/*
* updating the backend
*/.then((result) => {
const { errors, data } = result;
if (data) {
callback();
}
})
}
}
At the beginning of the submitForm()
function, the this.onSubmit.observers
is an Array containing one observer, like it should be.
As soon as it reaches the callback method, where the this.onSubmit.emit()
is invoked, the this.onSubmit.observers
is an Array containing ZERO observers.
I'm experiencing two very weird behaviors:
- If i remove the actual calling to update the backend in
SomeService.updateBackend
it works perfectly fine, and theobservers
still is an Array containing one observer! - If i keep the actual calling to the backend BUT not using
ngFor
and displaying only one<some-element>
it also works perfectly fine, keeping one observer in thethis.onSubmit.observers
within the callback scope!
Any idea what am i doing wrong?
Thanks in advance!
Update:
Thanks to @StevenLuke's comment about logging the ngOnDestroy
of SomeComponent
I found out that it is being destroyed before the emit.
Actually, the first thing it is doing when the SomeService.updateBackend
finishes is Destroying all the instances of this component and recreate them!
This is what makes the observers change! Why would that happen?