Search code examples
angularangular2-routingangular2-servicesngoninit

Angular ngOnInit - Refresh Needed


I have a web application. In my right side bar i have 3 posts. When i click on a post, i have a navigation:

    this.router.navigate(['../post', this.post.id]);

There a post profile component will take over. This component has a function that calls a function from a service that gets my post with the specified id. Now i will see all the details of that post in my content area (left part of the screen). This function(that gets my post) is called only in ngOnInit on the Post Profile component.

If i click on another post from my right side bar, i can see the change in url but the function that gets my post is not called and the post details from my content area are not changed. If i refresh the page now i can see the post that i want, everything works well.

I have .subscribe on my functions, if that helps.

I can't see the problem.

This is my PostProfileComponent

        constructor(postsService: PostsService, route: ActivatedRoute ) {
    this.postsService = postsService;

    this.routeSubscription = route.params
        .subscribe((params: any) => {
            this.postId = params['id'];
        });
}

public getPostById(id: any): void {
    this.postsService.getPostById(id)
        .map((response: Post) => {
            this.post = response;
            console.log(this.post);
        })
        .catch((error: any) => {
            return error;
        })
        .subscribe();
}

ngOnInit(): void {
    this.getPostById(this.postId);
}

Solution

  • In your Post Profile component's ngOnInit method you've to subscribe to the ActivatedRoute params Observable.

      subs1: Subscription;
      constructor(private route: ActivatedRoute){}
    
      ngOnInit() {
         this.subs1 = this.route.params
             .subscribe((params: Params) => {
                 const postId = params['id'] ? +params['id'] : '';
                 if(postId){
                    //  call the function (that gets the post)
                 }
             });
      }