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

时间:2017-05-24 20:55:13

标签: angular angular-router-guards

这是我的情景:

用户访问名为/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

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

1 个答案:

答案 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);

    }
}

更多信息: