I am a beginner when it comes to JS, TS, and Angular, and I have encountered an issue with an Angular component that I am working on:
export class AdminProductsMenuComponent implements OnInit{
constructor(private productService: ProductService,
private alertService: AlertService,
private router: Router) {
this.subscribeToDeleteProductEvents();
}
productsAdminModel: IGetProductAdminModel[] = [];
private productId: string;
ngOnInit(): void {
this.executeGetAllProductsAsAdmin();
}
executeGetAllProductsAsAdmin() {
this.productService.getAllProductsAsAdmin().subscribe({
next: (productData) => this.productsAdminModel = productData
})
}
private subscribeToDeleteProductEvents() {
this.alertService.getSubjectAlertEvent().subscribe({
next: (isConfirmed) => {
if (isConfirmed) {
this.productService.deleteProduct(this.productId).subscribe({
next: () => {
this.reloadCurrentResources();
}
});
}
}
});
}
private reloadCurrentResources(): void {
// save current route first
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate(['/AdminProducts']); // navigate to the same route
});
}
executeProductDelete(id: string) {
this.productId = id;
this.alertService.confirmationAlertProductDelete();
}
}
In summary: The constructor has a subscription in place to listen for events throughout the component's lifecycle.
An event is triggered by the last method called (via the template), which displays a SweetAlert confirmation dialog. Depending on the selection made, the event can be either true or false.
However, there seems to be an issue - if I move the executeProductDelete() method above reloadCurrentResources() and subscribeToDeleteProductEvents() and invoke it (executeProductDelete), an error occurs. https://i.sstatic.net/VXX7n.png
I suspect that it triggers once again the subscribeToDeleteProductEvents() and reloadCurrentResources().
If I keep executeDeleteProduct() as the final method, no error arises. Why is this happening? I think they are running synchronously and are not being called anywhere else.