根据Angular2

时间:2017-06-20 17:22:59

标签: angular angular2-routing

我正在使用Angualr2实现单页面应用程序。它应该能够在一个应用程序中处理多个用户角色。假设我有两个用户角色管理员员工和登录用户应该能够通过选择顶部下拉列表在这些角色之间切换。此外,每个角色在组件中包含不同的视图。 enter image description here

如上图所示默认情况下,用户已被分配到管理员角色。根据下拉选择左侧菜单,路径网址将更改如下。

dropDown Value= Admin
Home url =/home/admin
Reports url=reports/admin

if drop down value Employee
dropDown Value= Employee
Home url =/home/employee
Reports url=reports/employee

注意:这项工作完全没有当前的实现。但是如果我重新路由到相同的网址则存在问题。例如:假设当前下拉选项是管理,并且在主页视图中,如果我将下拉值更改为员工,请在同一视图中重新点击主菜单,它不会更新主页视图数据,即使我使用了 RoleService 。但网址已按预期更改。

(1)我的第一个问题是,我如何再次更新View以实现我的逻辑?

(2)我的第二个问题是如何在angaulr中获取当前URL并更新URL。例如:下拉选择是**管理员,在主页视图中,然后在同一视图中将下拉值更改为员工,因此网址应该从 / home /更改管理员 / home / employee 那么我怎样才能追加param值呢?**

左键菜单HTML

<a (click)="appNavigateTo('/home')">
          <span>Home</span>
 </a>
<a (click)="appNavigateTo('/reports')">
          <span>Reports</span>
 </a>

MenuComponent.tc

appNavigateTo(url: any) {
    this.router.navigate([url, this._roleService.getCurrentlyLoggedInRole()]);
  }

Route.ts

{ path: 'home/:role',         component: HomeComponent},
{ path: 'report/:role',         component: ReportComponent},

DropdownComponent.ts

export class DropdownComponent{

    construtor ( private _roleService : RoleService){}
    getSelectedRole( event: any ) {
        this._roleService.setCurrentlyLoggedInRole(event.target.value);
    }

}

RoleService.ts

static LOGGED_IN_ROLE= ROLE.ADMIN;
  /* Return the currently logged in role*/
  public getCurrentlyLoggedInRole(): String {
    return RoleService.LOGGED_IN_ROLE;
  }
  /*Set currently logged in role*/
  public setCurrentlyLoggedInRole(role: string): void {
    RoleService.LOGGED_IN_ROLE = role;
  }

请让我知道如何克服上述问题。感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

  1. 您可以通过订阅ngOnInit生命周期挂钩中的activatedRoute observable来更新视图。这允许你

    ngOnInit(){
        this._activatedRoute.params.subscribe(params => {
            // this is ran everytime the url changes
            // do whatever you need to update the view
        }
    }
    
  2. https://angular.io/api/router/ActivatedRoute

    1. 我对#2感到有点困惑。我认为查看路线快照https://angular.io/api/router/ActivatedRoute#members
    2. 可能是值得的