【问题标题】:Angular 2: TypeError: Cannot read property 'isRouteActive' of undefined inAngular 2:TypeError:无法读取未定义的属性“isRouteActive”
【发布时间】:2016-06-23 07:41:38
【问题描述】:

我正在尝试使用isRouteActive 函数在单击其中包含的链接时切换li 元素的active 类,但它不断给我类似TypeError: Cannot read property 'isRouteActive' of undefined in [isRouteActive(['./Home']) in AppComponent@6:16] 的错误。该文件如下所示:

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”、“/Home”、“./Home”、“Home”,但它们都不起作用。错误可能与什么有关?以及如何实际调试这种情况?

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    刚刚发布了问题,终于找到了答案:忘记在里面放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

    【讨论】:

      【解决方案2】:

      我会按照Angular 2: How to determine active route with parameters? 中的建议在&lt;a&gt; 元素上使用router-link-active

      干杯,

      大卫

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-19
        • 1970-01-01
        • 2014-11-29
        • 2018-10-29
        • 2021-07-21
        相关资源
        最近更新 更多