使用[routerLink]重定向到root时,请参考“ link.path”

时间:2019-03-13 10:37:30

标签: angular typescript

我有一个应用程序,该应用程序使用打字稿文件来设置链接,并且在模板中,我使用ngFor对链接进行插值并构建导航栏。在这些链接对象中,有一个名为link.path的属性,其中包含要重定向到的路径。我使用[routerLink]重定向到所需的路径,可以正常工作,但是我不在根URL上。我需要实现this功能,该功能将子路由附加到应用程序的根目录。但是,将实现更改为:

[routerLink]= '["/link.path"]'

点击后,我被重定向到<URL>/link.path而不是<URL>/<name under link.path>,这自然会给我一个未发现的错误。

如何更改上面的表达式以显示此参数内的实际值,而不是给我link.path作为字符串?

component.ts

// imports, declarations of classes and other stuff.

  * @property {array} links
  */
  links: Array<{ text: string, path: string }>;

  /**
  * constructor for toolbar component is responsible for initializing translatePipe, dynamic routing and router,
  * as well as adding routes dynamically to the router and the dynamicRouting service
  * @param translate
  * @param router
  * @param dynamicRouting
  *
  */
  constructor(private translate: TranslatePipe, private router: Router, private dynamicRouting: DynamicRoutingService) {
    this.router.config.unshift(
      { path: 'knowledge-base', component: DummyComponent },
      { path: 'home', component: DummyComponent },
      { path: 'settings', component: DummyComponent }
    );
    this.dynamicRouting.addItem({ text: "home", path: "home" });
    this.dynamicRouting.addItem({ text: "knowledge_base", path: "knowledge-base" });
    this.dynamicRouting.addItem({ text: "settings", path: "settings" });
  }
  /**
  * Upon initialization this function fetches the links and inserts the translated
  * text and path to be used by the template
  *
  * @param
  * @return
  */
  ngOnInit() {
    this.links = [];
    let rawData = this.dynamicRouting.getLinks();
    let self = this;
    rawData.forEach(function(data) {
      let text = self.translate.transform("generic[toolbar][categories][" + data.text + "][label]");
      self.links.push({ text: text, path: data.path });
    });

  //rest of the methods

html

<app-header
  [fixed]="true"
  [navbarBrandFull]="{src: 'assets/logo.png', width: 143, height: 36, alt: 'RT Logo'}"
  [navbarBrandMinimized]="{src: 'assets/logo2.png', width: 35, height: 35, alt: 'RT Logo'}"
  [sidebarToggler]="'lg'">
  <ul class="nav navbar-nav d-md-down-none" routerLinkActive="active">
    <li class="nav-item px-3" *ngFor="let link of links">
      <a class="nav-link" [routerLink]='["/link.path"]'>{{ link.text }}</a>
    </li>
  </ul>
  <ul class="nav navbar-nav ml-auto">
  </ul>
</app-header>

1 个答案:

答案 0 :(得分:1)

在Angular中,您可以针对任何路径撰写URL; [routerLink]提供了提供字符串标记或变量以构成最终路径的工具

  

[routerLink]="['/', var, 'str']" = /var/str

<a class="nav-link" [routerLink]='["/", link.path]'>{{ link.text }}</a>

RouterLink的官方角度参考:https://angular.io/api/router/RouterLink