Navigation to secondary route URL for routerLink attribute

微笑、不失礼 提交于 2019-12-24 11:05:05

问题


Angular supports primary routes as string attributes.

i.e.

<button routerlink="/path1">Click Me!</button>

However, when there are multiple outlets, adding a secondary route does not work:

<button routerlink="/path1(foo:/path2)">Click Me!</button>  <<-- does not work

Is there a way to make this work?

Note: I realize its possible to achieve this with:

<a [routerLink]="['/path1', { outlets: { foo: '/path2' } }]">Click Me!</a>

My question is more about whether this is possible using plain string attributes (the router framework could parse it behind the scenes).


回答1:


It doesn't seem to be possible with the current implementation of the router. When you pass a string to a routerLink it gets wrapped into an array here:

@Directive({selector: ':not(a)[routerLink]'})
export class RouterLink {
  ...

  }

  @Input()
  set routerLink(commands: any[]|string) {
    if (commands != null) {
      this.commands = Array.isArray(commands) ? commands : [commands]; <---------------
    } else {
      this.commands = [];
    }
  }

And here is the function that tries to parse the wrapped commands and extract outlets from it:

function getOutlets(commands: any[]): {[k: string]: any[]} {
  if (!(typeof commands[0] === 'object')) return {[PRIMARY_OUTLET]: commands};
  if (commands[0].outlets === undefined) return {[PRIMARY_OUTLET]: commands};
  return commands[0].outlets;
}

As you can see, if the value inside the wrapped commands is not an object - which is your case, it always defaults to primary outlet and uses the value as a path for this primary outlet:

if (!(typeof commands[0] === 'object')) return {[PRIMARY_OUTLET]: commands};


来源:https://stackoverflow.com/questions/45396130/navigation-to-secondary-route-url-for-routerlink-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!