【问题标题】:Route the Application based on Drop down Selection in Angular2根据 Angular2 中的下拉选择路由应用程序
【发布时间】:2023-04-06 10:28:01
【问题描述】:

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

如上图所示,默认用户已被分配到 Admin 角色。根据下拉选择左侧菜单路由 URL 将更改为如下所示。

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

注意:这在当前的实现中工作得非常好。但是如果我重新路由到相同的 url,就会出现问题。例如:假设当前下拉选择是 Admin 并且在 Home view 和同一视图中,如果我将下拉值更改为 Employee 并重新单击 Home menu 它不会更新主页视图数据,即使我使用了 RoleService。但网址按预期更改。

(1) 我的第一个问题是如何再次更新 View 任何 angaulr 生命周期钩子以实现我的逻辑?

(2) 我的第二个问题是如何在 angaulr 中获取当前 URL 并更新 url。例如:下拉选择是 **Admin 并且在 主页视图 然后在同一个视图中将下拉值更改为 Employee 并且结果 url 应该从 /home/ admin/home/employee 那么我怎样才能只附加参数值?**

左侧菜单 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;
  }

请告诉我如何克服上述问题。感谢任何帮助。

【问题讨论】:

    标签: angular angular2-routing


    【解决方案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
          }
      }
      

    https://angular.io/api/router/ActivatedRoute

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多