这是我的情景:
用户访问名为/protected
的路线。在我的CanActivate警卫中,我检查用户是否已登录。如果他们未登录,我想渲染我的404
路线,但仍然显示地址栏中显示/protected
。我希望用户无法区分受保护的页面和不存在的页面。
这是我尝试过但不起作用的。
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private router: Router, private userService: UserService) {}
canActivate() {
if (this.userService.getUser()) return true;
this.router.navigate(['/404']);
return false;
}
}
路由后,地址栏中的网址会显示/404
,但我希望它显示/protected
。
更改为this.router.navigate(['/404'], { skipLocationChange: true });
也不起作用,因为地址栏中的网址将是之前的网址,而不是/protected
。
我的问题是:如果用户没有登录,同时仍保留他们试图在地址栏中访问的网址,您如何呈现不同的组件?
答案 0 :(得分:1)
如果用户未登录,/protected
路由应呈现错误组件,否则呈现不同的组件。
为/protected
,/error
和/page1
定义路线和组件。
当用户登陆/protected
时,如果他们没有登录,请导航至/error
,否则/page1
。
务必将{ skipLocationChange: true }
作为第二个参数传递给路由器,以避免网址导航离开/protected.
this.router.navigate([this.url], { skipLocationChange: true });
为CanActivate()
添加/protected
检查确定您是否可以访问路径。因此,在这种情况下它没有用,因为您希望路径是开放的但显示不同的内容。
https://plnkr.co/edit/6o2DPXmYfNiQEW2Kbr8A?p=preview
@Component({
selector: 'app-protected',
template: `
Location: {{href}} <br>
Checking Login state ...
<div *ngIf="url">Switching to {{url}}</div>
`,
})
export class AppProtected implements OnInit {
url : string;
href = window.location.href;
constructor(private router : Router ) {
}
ngOnInit(){
const isUserLoggedIn = /true/.test(localStorage.getItem('isUserLoggedIn'));
this.url = isUserLoggedIn ? '/page1' : '/error';
window.setTimeout(() => {
this.router.navigate([this.url], { skipLocationChange: true });
}, 2000);
}
}