Angular 2路由器可以激活如何重定向到404,但仍然显示正在访问的url

Angular 2路由器可以激活如何重定向到404,但仍然显示正在访问的url,angular,angular-router-guards,Angular,Angular Router Guards,以下是我的设想: 用户访问名为/protected的路由。在我的CanActivate guard中,我检查用户是否登录。如果他们没有登录,我想呈现我的404路线,但仍在地址栏中显示/protected。我希望用户无法区分受保护的页面和不存在的页面 这是我尝试过的,但不起作用 @Injectable() export class LoggedInGuard implements CanActivate { constructor(private router: Router, private

以下是我的设想:

用户访问名为
/protected
的路由。在我的CanActivate guard中,我检查用户是否登录。如果他们没有登录,我想呈现我的
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保留在地址栏中,如何呈现不同的组件?

问题: 如果用户未登录,
/protected
路由应呈现错误组件,否则呈现其他组件

可能的解决办法: 为
/protected
/error
/page1
定义路由和组件。 当用户登录到
/protected
时,如果他们没有登录,请导航到
/error
,否则
/page1

确保将
{skipLocationChange:true}
作为第二个参数传递给路由器,以避免url导航到
/protected之外。

this.router.navigate([this.url], { skipLocationChange: true });
注: 添加
CanActivate()
检查
/protected
可确定是否可以访问路径。因此,在这种情况下它没有用处,因为您希望路径是开放的,但显示不同的内容

演示:

示例代码
@组件({
选择器:“应用程序受保护”,
模板:`
位置:{{href}}
正在检查登录状态。。。 切换到{{url} `, }) 导出类AppProtected实现OnInit{ url:string; href=window.location.href; 构造函数(专用路由器:路由器){ } 恩戈尼尼特(){ const isUserLoggedIn=/true/.test(localStorage.getItem('isUserLoggedIn')); this.url=isUserLoggedIn?'/page1':'/error'; window.setTimeout(()=>{ this.router.navigate([this.url],{skipLocationChange:true}); }, 2000); } }
更多信息:

我认为您可以通过在同一模板中使用两个路由器插座来实现这一点,这样您就可以在两个不同组件之间切换,而无需更改路由。你能用你当前的代码创建一个plunker让我试试吗?不过我不想使用两个路由器插座。我希望angular有一面旗帜或是什么我不知道的东西来做这件事。我想你的答案在这里
@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);

    }
}