Angular2 - Directive - RouterLink

/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'User' }
* ]);
* class MyComp {}
*
*
* When linking to this `User` route, you can write:
*
*
* <a [routerLink]="['./User']">link to user component</a>
*
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/Team', {teamId: 1}, 'User', {userId: 2}]`
* means that we want to generate a link for the `Team` route with params `{teamId: 1}`,
* and with a child route `User` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/

来中文

  • routerLink 接受的是一个数组, 希望是得到一个 路由名字 参数 子路由名字 子路由参数

说到子路由

上例子
根路由配置

 <li (click)="loopNav($event)"> <a [routerLink]="['ParentApp','NumberList']">ParentApp</a></li>
...
{ path: '/ParentApp/...', name: 'ParentApp', component: ParentApp }

子组件中子路由配置

     <li> <a [routerLink]="['./NumberList']">NumberList</a></li>
<li> <a [routerLink]="['./NumberItem']">NumberItem</a></li>
...
@RouteConfig([
{ path: '/', name: 'NumberList', component: numberList ,useAsDefault: true},
{ path: '/numberItem', name: 'NumberItem', component: numberItem }
])

父路由中的 ‘…’ 是根据报错信息加上的。具体原因要看源码中哪里有用到

来自官网:
Notice that the path ends with a slash and three trailing periods (/…).
That means this is an incomplete route (a non-terminal route). The finished route will be some combination of the parent /crisis-center/ route and a route from the child router that belongs to the designated component.

https://github.com/dreambo8563/node_angular2/blob/ng-pages/app/components/CompLoaderSample.ts

源码

@Directive({
selector: '[routerLink]',
inputs: ['routeParams: routerLink', 'target: target'],
host: {
'(click)': 'onClick()',
'[attr.href]': 'visibleHref',
'[class.router-link-active]': 'isRouteActive'
}
})
export class RouterLink {
private _routeParams: any[];

// the url displayed on the anchor element.
visibleHref: string;
target: string;

// the instruction passed to the router to navigate
private _navigationInstruction: Instruction;

constructor(private _router: Router, private _location: Location) {
// we need to update the link whenever a route changes to account for aux routes
this._router.subscribe((_) => this._updateLink());
}

// because auxiliary links take existing primary and auxiliary routes into account,
// we need to update the link whenever params or other routes change.
private _updateLink(): void {
this._navigationInstruction = this._router.generate(this._routeParams);
var navigationHref = this._navigationInstruction.toLinkUrl();
this.visibleHref = this._location.prepareExternalUrl(navigationHref);
}

get isRouteActive(): boolean { return this._router.isRouteActive(this._navigationInstruction); }

set routeParams(changes: any[]) {
this._routeParams = changes;
this._updateLink();
}

onClick(): boolean {
// If no target, or if target is _self, prevent default browser behavior
if (!isString(this.target) || this.target == '_self') {
this._router.navigateByInstruction(this._navigationInstruction);
return false;
}
return true;
}
}

看能延伸出什么其他的东西:

  • annotation
    @Directive({
    selector: '[routerLink]',
    inputs: ['routeParams: routerLink', 'target: target'],
    host: {
    '(click)': 'onClick()',
    '[attr.href]': 'visibleHref',
    '[class.router-link-active]': 'isRouteActive'
    }
    })

值得一说的就是 inputs- routeParams 接受上面说的数组参数。(路由子路由 参数什么)
target - 来自w3c school

-  _blank    在新窗口中打开被链接文档。
- _self    默认。在相同的框架中打开被链接文档。
- _parent    在父框架集中打开被链接文档。
- _top    在整个窗口中打开被链接文档。
- framename    在指定的框架中打开被链接文档。

visibleHref: string;

当路由link需要当做anchor 的时候需要 href 属性

”aux routes“ 这个后面应该有单独的class 说

this._navigationInstruction = this._router.generate(this._routeParams);
var navigationHref = this._navigationInstruction.toLinkUrl();
this.visibleHref = this._location.prepareExternalUrl(navigationHref);

根据inputs 产生 Instruction
转换成url 因为有子路由神马的,参数的
根据你的策略生成外面看到的url
下面是 prepareExternalUrl 的作用

/**
* Given a string representing a URL, returns the platform-specific external URL path.
* If the given URL doesn't begin with a leading slash (`'/'`), this method adds one
* before normalizing. This method will also add a hash if `HashLocationStrategy` is
* used, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
*/


get isRouteActive(): boolean { return this._router.isRouteActive(this._navigationInstruction); }

从这句可知,想要知道哪个路由是是否active 可以

- 把当前路由参数变成 Instruction
- 在根据this._router.isRouteActive 方法来判断

this._router.navigateByInstruction(this._navigationInstruction);

onclick中代码可以学到 ,当你得到某个 instruction的时候,你可以用代码跳转
this._router.navigateByInstruction

Instruction 的简单介绍

 * `Instruction` is a tree of {@link ComponentInstruction}s with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* `Instruction`s can be created using {@link Router#generate}, and can be used to
* perform route changes with {@link Router#navigateByInstruction}.