2016-09-04 65 views
1

我仍然使用alpha8路由器。我有3條主要航線有:路由器angular2不能使用相同的組件,但difefrenet id

export const appRoutes: RouterConfig = [ 
    { path: '', component: LandingComponent }, 
    { path: 'blog', component: BlogComponent }, 
    { path: 'posts/:id', component: PostComponent }, 
    { path: 'posts', redirectTo: 'blog' }, 
    { path: '**', redirectTo: ''} 
]; 

所以我有精選文章和鏈接組件沒有從BlogComponent工作得很好,但是當這個組件是PostComponent,ID只能改變URL地址。 這是鏈接看起來怎麼樣在該組件

<a [routerLink]="['/posts/'+post.id]">...</a>

所以,當我們在localhost:5000/blog其路由罰款localhost:5000/posts/19 f.ex.但從localhost:5000/posts/19它不去localhost:5000/posts/20。它只會改變網址,contstructor,ngOnInit不會被執行。我怎麼解決這個問題?

回答

3

你必須在ngOnInit中添加一個「訂閱者」來捕捉url參數的變化。此外,您應該在ngOnDestroy內部取消訂閱(在您的組件類中實現此操作,就像您使用OnInit一樣),以避免內存泄漏。

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { ActivatedRoute } from '@angular/router'; 

@Component({ 
    selector: 'your-posts-component' 
}) 
export class PostsComponent implements OnInit, OnDestroy { 

private sub: any; 

constructor(private route: ActivatedRoute) {} 

// add a subscriber to watch for changes in the url 
ngOnInit() { 
    this.sub = this.route.params 
     .subscribe(params => { 
      // get id from params 
      let id = +params['id']; 

      // do whatever you want with id here 

     }); 
     } 
} 

// unsubscribe to avoid memory leaks 
ngOnDestroy() { 
    this.sub.unsubscribe(); 
} 

這是如何在組件已經不通過其它部件重新檢測到上網址參數的變化。

相關問題