Search code examples
angularquery-stringangular-activatedroute

Cannot receive queryparameters sent in Angular routing


I have a component that routes to another component passing some conditional parameters

This the code that defines the routing:

redirect(topicname : string){
    alert(topicname)
    this.router.navigate(['/chapters'], { queryParams: { topic: topicname } });
  }

And on the Chapters.component.ts file I have defined:

export class ChapterstemplComponent implements OnInit {
  topic : string;
  constructor( private route : ActivatedRoute) { 
    this.topic= this.route.snapshot.params.topic;
    alert( this.route.snapshot)
  }

But this.topic does not receive any value. I want to use it in my HTML file of chapters.component. NOTE: The alert messages confirm that 'topicname' was sent well in the first snippet But in the second snippet, the route did not receive any parameters Here is the image for the same:

1st/sending alert: enter image description here

2nd/receiving alert: enter image description here


Solution

  • We can get query params with the help of paramMap

    Try to do something like below, which will get the params in subscription of queryParams of ActivatedRoute.

    ngOnInit() {
     this.route.queryParams.subscribe(params => {
        this.topic = params['topic'];
      });
    }
    

    You can also read more about routing in detail here: navigate-to-other-page

    Happy Coding.. :)