2016-03-09 32 views
2

我試圖用isRouteActive功能在點擊其中包含的鏈接到activeli元素的開關讀取屬性「isRouteActive」的定義,但它一直給我像TypeError: Cannot read property 'isRouteActive' of undefined in [isRouteActive(['./Home']) in [email protected]:16]錯誤。該文件看起來像下面這樣:角2:類型錯誤:無法在

import {Component} from 'angular2/core'; 
import {ROUTER_DIRECTIVES, RouteConfig, Router } from 'angular2/router'; 
import {FORM_PROVIDERS, FORM_DIRECTIVES, Control} from 'angular2/common'; 
import {LoginComponent} from './login.component.js'; 
import {HomeComponent} from './home.component.js'; 

@Component({ 
selector: 'front-page-app', 
providers: [ FORM_PROVIDERS ], 
directives: [ ROUTER_DIRECTIVES, FORM_DIRECTIVES ], 
template: ` 
<div class="container"> 
    <div class="header clearfix"> 
    <nav> 
     <ul class="nav nav-pills pull-right"> 
     <li #homeLink role="presentation" 
      [class.active]="isRouteActive(['./Home'])"> 
     <a [routerLink]="['./Home']">Home</a> 
     </li> 
     <li #loginLink role="presentation" 
      [class.active]="isRouteActive(['./Login'])"> 
     <a [routerLink]="['./Login']">Login</a> 
     </li> 
     </ul> 
    </nav> 
    <h3 class="text-muted">Fomoapp</h3> 
    </div> 
</div> <!-- /container --> 
<router-outlet></router-outlet> 
` 
}) 

@RouteConfig([ 
{ path: '/login', component: LoginComponent, name: 'Login' }, 
{ path: '/home', component: HomeComponent, name: 'Home' }, 
{ path: '/', redirectTo: ['Home'] } 
]) 
export class AppComponent { 
public isRouteActive(route) { 
    return this.router.isRouteActive(this.router.generate(route)) 
} 
} 

我嘗試了多種途徑,像一個 '/ home', '#/家', '/主頁', './Home', '家',但沒有的他們工作。錯誤可能與什麼有關?以及如何真正調試這種情況?

回答

4

剛發佈的問題,最後找到答案:忘了把constructor和供應Router在它。因此,工作版本改變export class Appcomponent一部分,並期待通過以下方式:

export class AppComponent { 
    constructor(private router: Router) { 
    } 

    public isRouteActive(route) { 
     return this.router.isRouteActive(this.router.generate(route)) 
    } 
} 

另見the link