2016-02-12 99 views
1

當我在試驗Angular2的路由器(2.0 beta 6)時,我遇到了一個有關從子組件調用routeLink(或router.navigate)的問題。來自子組件的Angular2路由鏈接不起作用

我的主要成分是這樣的:

@Component({ 
    selector: 'myapp', 
    template:` 
    <div> 
    <alink></alink> 
    <router-outlet></router-outlet> 
    </div> 
    `, 
    directives: [ROUTER_DIRECTIVES, ALinkComponent], 
    providers: [ROUTER_PROVIDERS] 
}) 
@RouteConfig([ 
    { 
     path: '/first', 
     name: 'First', 
     component: FirstComponent, 
     useAsDefault: true 
    }, 
    { 
     path: '/second', 
     name: 'Second', 
     component: SecondComponent 
    } 
]) 
export class MyApp { 
} 

<alink>只顯示有[routerLink]Second鏈接:

@Component({ 
    selector: 'alink', 
    template: `<h3><a [routerLink]="['Second']">Should redirect to second</a></h3>`, 
    directives: [ROUTER_DIRECTIVES], 
    providers: [ROUTER_PROVIDERS] 
}) 
export class ALinkComponent { 
} 

然而,這種點擊鏈接時,沒有任何反應,甚至一個(不消息彈出在控制檯上)。來自MyApp模板的鏈接完美地發現。使用(click)=...處理程序與router.navigate(...)也不起作用。

爲了使routerLink可以在任何嵌套組件中工作,需要更改哪些內容?

完整的例子就是提供on Plunker

回答

1

我得到了你的榜樣工作here,但我不得不添加的代碼中有相當。問題是ALinkComponent沒有自己的RouteConfig,所以它需要訪問MyApp的路由器並調用它的navigate方法。

+0

非常感謝您的工作!您注入父母並使用其路由器的想法實際上使我走上了正確的道路。我只是發現另一種方式,這對我來說似乎更容易,但在某些情況下,migh有缺點:http://stackoverflow.com/a/35369679/2597135 –

1

基於@MattScarpino's answer非常有幫助的答案,this blogpost我能想出這樣做的更簡單的方法,而無需直接注入MyApp

@Component({ 
    selector: 'alink', 
    template: `<h3><a (click)="viewSecond()">Should redirect to second but does not</a></h3>`, 
    directives: [ROUTER_DIRECTIVES], 
    providers: [ROUTER_PROVIDERS] 
}) 
export class ALinkComponent { 
    constructor(injector: Injector) { 
    this.router = injector.parent.get(Router); 
    } 

    viewSecond() { 
    this.router.navigate(["Second"]) 
    } 
} 

這種解決方案的缺點是可能的,我們可能需要使用parentparent.parent視情況而定。但是,我們避免顯式引用頂級組件。