NodeJS 是否有可能扩展此代码,如有超过2个选项?

ulydmbyx  于 2023-02-21  发布在  Node.js
关注(0)|答案(1)|浏览(74)

下面是我的代码来获得每个标题:

export class WrapperComponent implements OnInit, OnDestroy {
  DASHBOARD = 'Dashboard'
  DASHBOARD_URL = 'dashboard'
  PERSONAL_INFORMATION = 'Personal Information'
  PERSONAL_INFORMATION_URL = 'personal-information'
  EMPLOYEE_HISTORY = 'Employee History'
  EMPLOYEE_HISTORY_URL = 'employee-history'
  navBarTitle = this.DASHBOARD
  subs: Subscription[] = [];
  constructor(private router: Router) {}

  ngOnInit(): void {
    this.subToRouterEvents();
  }

  ngOnDestroy(): void {
    if (0 === this.subs.length) {
      return;
    }
    this.subs.forEach((sub) => sub.unsubscribe());
  }

  subToRouterEvents() {
    const routeEventSub = this.router.events.subscribe(this.routerEventHandler);
    this.subs.push(routeEventSub);
  }

  routerEventHandler = (event: Event) => {
    if (event instanceof NavigationEnd) {
      const routeText = this.router.url.split('/');
      this.evalRouteUrl(routeText[3]);
    }
  };
  evalRouteUrl(url: string) {
    if ('undefined' === typeof url) return;
    this.navBarTitle = url === this.DASHBOARD_URL ? this.DASHBOARD : this.PERSONAL_INFORMATION
  }
}

这是我的html代码:

<nav aria-label="breadcrumb">
      <ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
        <li class="breadcrumb-item text-sm" *ngIf="navBarTitle === 'Personal Information'">
          <a class="opacity-5 text-white">My Account</a>
        </li>
        <li
          class="breadcrumb-item text-sm text-white active"
          aria-current="page" *ngIf="navBarTitle === 'Personal Information'"
        >
          My Profile
        </li>
        <li
          class="breadcrumb-item text-sm text-white active"
          aria-current="page"
        >
          {{ navBarTitle }}
        </li>
      </ol>
      <h6 class="font-weight-bolder text-white mb-0 text-uppercase">
        {{ navBarTitle }}
      </h6>
    </nav>

任何人都可以帮助我得到导航栏的标题...我有这个代码,但它只需要2个选项。这将是一个很大的帮助我。
是否有可能扩展此代码,如有超过2个选项?

evalRouteUrl(url: string) {
    if ('undefined' === typeof url) return;
    this.navBarTitle = url === this.DASHBOARD_URL ? this.DASHBOARD : this.PERSONAL_INFORMATION
  }
pqwbnv8z

pqwbnv8z1#

请不要使用图片来显示代码,否则请编写代码,选择所有并使用Ctrl+K来格式化它(很难阅读带有图片的问题)
你应该“参数化你的应用程序”,也就是使用一个对象数组
如果你有一个数组

paths=[{path:'dashboard', title:'Dashboard'},
       {path:'personal-information', title:'Personal Information'},
       ...
      ]

可以通过路径在数组中查找并返回标题

evalRouter(url:string)
{
   const path=this.paths.find(x=>x.path==url)
   this.navBarTitle=path?path.title:''
}

顺便说一句:您可以使用新的属性(从Angular 15 -在以下版本中,您使用“数据”属性-)标题在您的路线,例如。

const routes=[{
  path: 'dashboard',
  component: DashboardComponent,
  title:'Dashboard'
}, {
  path: 'personal-information',
  component: PersonalInfoComponent,
  title:'Dashboard'
}
...
]

相关问题