在调用弹出窗口的地方添加用户事件(比如监听点击事件),然后在回调函数中打开弹出窗口。这样浏览器就不会将其视为无效弹出窗口。
示例代码:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
return this.checkLogin().then((isLoggedIn) => {
if (isLoggedIn) {
return true;
} else {
// 添加用户事件
document.addEventListener('click', () => {
// 在回调函数中打开弹出窗口
window.open('https://example.com/login');
});
return false;
}
});
}
checkLogin(): Promise {
// 实现登录判断逻辑
}
}
注意:这种解法并不是在所有浏览器中都适用,因为一些浏览器可能对用户事件也进行拦截。对于这种情况,最好的解决方案是不要使用弹出窗口,而是使用模态框或其他交互组件。