Oleksii Kryzh Oleksii Kryzh - 3 months ago 12
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
localhost:5000/blog
it routes fine to
localhost:5000/posts/19
f.ex. But from
localhost:5000/posts/19
it does not go to
localhost:5000/posts/20
. It only changes the url,
contstructor
,
ngOnInit
are not executed. How can I solve this problem?

Answer

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';

@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();
}

This is how changes on url params are detected when a component has been revisited without passing through another component.

Comments