Angular 2: TypeError: Cannot read property 'is

2019-07-12 08:34发布

I am trying to use isRouteActive function to switch the active class of the li elements upon clicking the links contained within them, but it keeps giving me the errors like TypeError: Cannot read property 'isRouteActive' of undefined in [isRouteActive(['./Home']) in AppComponent@6:16]. The file looks like the following:

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))
}
}

I tried a variety of paths, like '/home', '#/home', '/Home', './Home', 'Home' but none of them work. What the error could be related to? And how to actually debug such situations?

2条回答
成全新的幸福
2楼-- · 2019-07-12 08:56

Just posted the question and finally found the answer: forgot to put constructor and supply Router in it. So, working version changes export class Appcomponent part and looks the following way:

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

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

Also see the link.

查看更多
闹够了就滚
3楼-- · 2019-07-12 09:04

I would use router-link-active on the <a> element as suggested in Angular 2: How to determine active route with parameters? .

Cheers,

David

查看更多
登录 后发表回答