Angular 2:TypeError:无法读取未定义的属性'isRouteActive'

时间:2016-03-09 04:38:56

标签: angular angular2-routing

我正在尝试使用isRouteActive函数在点击其中包含的链接时切换active元素的li类,但它会一直给我{{1}这样的错误}}。该文件如下所示:

TypeError: Cannot read property 'isRouteActive' of undefined in [isRouteActive(['./Home']) in AppComponent@6:16]

我试过各种各样的路径,比如'/ home','#/ home','/ Home','。/ Home','Home',但它们都不起作用。这个错误可能与什么有关?以及如何实际调试这种情况?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

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

干杯,

大卫