2

这是我的场景:

用户访问名为 的路线/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;
  }
}

路由后,地址栏中的url会显示/404,但我希望它显示/protected

更改为this.router.navigate(['/404'], { skipLocationChange: true });也不起作用,因为地址栏中的 url 将是以前的 url,而不是/protected.

我的问题是:如果用户未登录同时仍将他们试图访问的 url 保留在地址栏中,您如何呈现不同的组件?

4

1 回答 1

2

问题:

/protected如果用户未登录,路由应该呈现错误组件,否则呈现不同的组件。

可能的解决方案:

/protected为、/error和定义路由和组件/page1。当用户登陆时,如果他们没有登录/protected,导航到,否则导航到。/error/page1

一定要{ skipLocationChange: true }作为第二个参数传递给路由器,以避免 url 导航离开/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);

    }
}

更多信息:

于 2017-05-24T23:45:18.623 回答