Oleksii Kryzh Oleksii Kryzh - 1 month ago 10
TypeScript Question

Router angular2 does not work with the same component but difefrenet id

I am still using alpha8 router. I have 3 main routes:

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

So I have a component with featured posts and links there work pretty fine from the BlogComponent, but when this component is in PostComponent, id only changes the url address.
This is how links look like in that component

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

So when we are at
it routes fine to
f.ex. But from
it does not go to
. It only changes the url,
are not executed. How can I solve this problem?


You have to add a "subscriber" inside the ngOnInit to catch changes in url params. Also, you should unsubscribe inside the ngOnDestroy (implement this to your component class, as you do with OnInit), in order to avoid memory leaks.

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

    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 is how changes on url params are detected when a component has been revisited without passing through another component.