订阅新Angular 2路由器的更改(> = rc1)

时间:2016-05-30 10:26:55

标签: angular angular2-routing

为了验证我的Angular 2应用程序,我在应用程序初始化中订阅了我的路由器。我检查用户是否已设置,如果不是,我尝试从我的登录服务中获取用户,如果这也不可能,我想进入登录页面。

ngOnInit() {
    this._router.changes.subscribe(
        next => {
            // First check if our component has a user set
            if (this.loggedInUser === undefined) {
                // It doesn't, let's set this user with help from our loginService
                this.loggedInUser = this._loginService.getUser();

------->        I think that this is where I need to add a line like: 
       if the user now is logged in, finish the change that triggered this code.

                // If user stil isn't set, we need to login
                if (this.loggedInUser === undefined) {
                    // Check if the user isn't already at the login page
                    if (!(this._router.urlTree.contains(this._router.createUrlTree(['login'])))) {
                        console.log('Not authorised, redirected to login.');
                        this._router.navigate(['login']);
                    }
                }
            }
        }
    );
}

此解决方案的问题是我的应用程序中的硬链接不再起作用。

例如: 如果我转到localhost:8000 / user / 1我的应用程序已初始化,我的应用程序从我的loginService获取用户。但它不会转到我输入的链接,我可以通过菜单导航到该用户。我想我需要添加一行告诉路由器它应该遵循下一个动作?这种结构有可能吗?

编辑:我希望这个解释更清楚问题: 如果我转到某个网址,例如http://aplication/users/5,则会触发上面的代码段。大多数情况下,用户已经登录并从loginService检索凭据。如何告诉路由器它应该只完成触发代码的更改操作?

1 个答案:

答案 0 :(得分:0)

我说return;应该做你想做的事。 "触发此代码的更改"到目前为止已经完成了。如果您没有明确导航到另一条路径,这应该是您要求的结果。