Angular 11使用ng snotify登录成功不显示toast及弹窗异常问题
问题根因
1. 登录成功无提示
调用SnotifyService.success后立刻执行this.router.navigateByUrl('/db')跳转路由,登录组件被快速销毁,挂载在登录组件DOM下的Snotify提示容器也被同步移除,导致用户看不到成功提示。
2. 空凭证偶尔同时弹出两个提示
- 触发
signIn方法时首先将loading设为true,空校验分支又立刻将loading重置为false,若用户快速点击提交按钮,会重复触发signIn方法 - 空校验分支未显式return,极端场景下可能出现逻辑穿透
解决方案
具体修改点
- 路由跳转增加短延迟,保证成功提示可被用户观察到
- 提交按钮绑定
[disabled]="loading"属性,避免重复点击触发多次提交 - 空校验分支增加显式return终止逻辑,同时将
$event.preventDefault()移到方法最开始统一处理 - 调整loading状态的赋值逻辑,避免空校验场景下loading快速闪变
修改后代码示例
signIn($event: any, email: string, pass: string): void { // 统一阻止表单默认提交行为 $event.preventDefault(); // 已有提交请求在处理中则直接返回,避免重复触发 if (this.loading) return; this.loading = true; const data = { userName: email, password: pass }; if (data.userName === '' || data.password === '') { this.snotifyService.warning('Username & Password cannot be empty', '', { timeout: 7000, showProgressBar: false, closeOnClick: false, pauseOnHover: true }); this.loading = false; // 显式return终止后续逻辑 return; } this.authService.logIn(data).subscribe(response => { this.loading = false; if (response.isValid == true) { this.cookieService.set('username', response.username); this.cookieService.set('password', response.username); this.cookieService.set('userId', response.id); this.cookieService.set('isLoggedIn', response.isValid); this.snotifyService.success('Logged in successfully!', '', { timeout: 7000, showProgressBar: false, closeOnClick: false, pauseOnHover: true }); // 增加800毫秒延迟再跳转路由,保证提示正常显示后再跳转 setTimeout(() => { this.router.navigateByUrl('/db'); }, 800); } else { this.snotifyService.error('Invalid Username or Password !', '', { timeout: 7000, showProgressBar: false, closeOnClick: false, pauseOnHover: true }); } }, error => { this.loading = false; }); }
可选优化方案
如果不想用setTimeout做延迟跳转,也可以将ng-snotify的全局容器挂载到应用根组件(app.component.html)中,这样路由切换时Snotify容器不会被销毁,所有页面的提示都可以正常显示。
内容的提问来源于stack exchange,提问作者Mohit Kumar Sharma
相关产品推荐
相关产品推荐

