I have a form in angular and when it is submitted, there is a redirection to homepage after X seconds.
Here is the service containing the redirection method:
export class RouterService { private unsubscribe: Subject<void> = new Subject(); constructor(private router: Router) {} ngOnDestroy() { this.unsubscribe.next(); this.unsubscribe.complete(); } redirectToHome() { timer(REDIRECT_TIMEOUT_MS) .pipe(takeUntil(this.unsubscribe)) .subscribe((_) => { this.router.navigate(['/']); }); } }
Here is the submit method:
this.missionService .createMission(mission) .pipe(takeUntil(this.unsubscribe)) .subscribe({ next: (response) => { this.messageService.add({ severity: 'success', summary: 'Mission created successfully', detail: '', life: 5000, }); this.routerService.redirectToHome(); }, error: (error) => { this.messageService.add({ severity: 'error', summary: error.error.reason, detail: error.error.message, life: 5000, }); }, });
I’d like to know how can I stop redirectToHome() if suppose an user click somewhere else in the menu before x seconds have elapsed.
Advertisement
Answer
I’d add an cancelNavigation subject in your service which would cancel navigation if called.
public cancelNavigation$ = new Subject<void>(); redirectToHome() { timer(REDIRECT_TIMEOUT_MS) .pipe( takeUntil(this.unsubscribe), takeUntil(this.cancelNavigation$) ) .subscribe((_) => { this.router.navigate(['/']); }); }