javascript - Angular2 组件不检测路由参数更新(路由器 3.0)

标签 javascript angular angular2-routing angular2-components angular2-router3

我有一个小 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/

相关文章:

angular - 行数据中的 ag-grid routerlink 导致模板中断

angular2-routing - 我们可以用角度从另一个项目中路由一个项目吗

angular - routerLink 的相对链接/部分路由

javascript - 如何使用 javascript 和 regex 从标签 div 获取 id 值?

angular - ng build --prod 非导出函数

angular - 错误 : Schema validation failed with the following errors: Data path ".builders[' app-shell' ]"should have required property ' class'

Angular 项目更新

Javascript:对象复制、全局变量和性能

javascript - 如何将我的模块 Javascript 添加到 Prestashop 中的*所有*页面?

javascript - Firefox 扩展中的不透明度和 jQuery 淡入/淡出