我有一个小 Plunk,我正在使用它来玩转 Angular 2 目前可用的新 Router 3.0 alpha。它通常运行良好,但问题是一旦我点击一个链接路由到具有特定 ID 的“详细信息”组件,当我单击具有不同 ID 的不同链接时,它永远不会改变。该组件永远不会被重新实例化,因此它只会显示它在第一次加载时传递的内容。
这是有问题的组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ContactsService } from './contacts.service';
@Component({
selector: 'contacts-detail',
template: `
<h2>{{contact.name}}</h2>
`
})
export class ContactsDetailComponent implements OnInit {
constructor(private contactsService: ContactsService, private route: ActivatedRoute) {
}
ngOnInit() {
this.contact = this.contactsService.getContact(this.route.snapshot.params.id);
console.log('Fetching user', this.route.snapshot.params.id);
}
}
Here is the Plunk证明问题。单击一个作者姓名,然后单击另一个作者姓名,看它没有改变。
最佳答案
在您的 ContactsDetailComponent
中,将 OnInit
更改为:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id'];
this.contact = this.contactsService.getContact(id);
});
}
在你的 Plunk 中为我工作。
关于javascript - Angular2 组件不检测路由参数更新(路由器 3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38015385/