角2:类型错误:无法读取的未定义的属性'isRouteActive“在 [英] Angular 2: TypeError: Cannot read property 'isRouteActive' of undefined in
问题描述
我想使用 isRouteActive
功能切换有效
类的<code>李在单击其中包含的链接元素,但它一直给我像错误类型错误:在[isRouteActive([无法读取的未定义的属性'isRouteActive'./家 ])在AppComponent @ 6:16]
。该文件看起来像下面这样:
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))
}
}
我尝试了各种路径,如/家','#/家','/家庭','./Home','家',但他们没有工作。什么错误可能与?而如何真正调试这种情况?
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?
推荐答案
刚刚发布的问题,终于找到了答案:忘了构造
和供应路由器
在里面。因此,工作版本修改出口类Appcomponent
部分,看起来下列方式:
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))
}
}
另见链接:<一个href=\"http://ux.$c$cover.org/questions/34925782/angular2-routing-persisting-route-tabs-and-child-routes\" rel=\"nofollow\">http://ux.$c$cover.org/questions/34925782/angular2-routing-persisting-route-tabs-and-child-routes
这篇关于角2:类型错误:无法读取的未定义的属性'isRouteActive“在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!