我有一個 Angular 表單,提交后,X 秒后重定向到主頁。
這是包含重定向方法的服務:
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(['/']);
});
}
}
這是提交方法:
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,
});
},
});
如果假設用戶在 x 秒過去之前單擊選單中的其他位置,我想知道如何停止 redirectToHome() 。
uj5u.com熱心網友回復:
我會在您的服務中添加一個 cancelNavigation 主題,如果呼叫它會取消導航。
public cancelNavigation$ = new Subject<void>();
redirectToHome() {
timer(REDIRECT_TIMEOUT_MS)
.pipe(
takeUntil(this.unsubscribe),
takeUntil(this.cancelNavigation$)
)
.subscribe((_) => {
this.router.navigate(['/']);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518183.html
上一篇:Angular13ngserve不支持:關鍵字“id”,使用“$id”作為模式ID
下一篇:將本地json讀入介面型別陣列
