0

I followed this answer: How to get query params from url in Angular 2?, and am not sure how they were able to test by entering http://localhost:4200?test=hi. Please give advice - this does not work for me.

I have an AppComponent and a router which routes to OrderComponent. I need to get the query parameter from the URL in the AppComponent and pass the same to the OrderComponent.

aabbcc
  • 19
  • 1
  • 8

1 Answers1

0

In the ngOnInit method of your component class you can do the following:

  constructor(private route: ActivatedRoute){}

  ngOnInit(){
      this.route.queryParamMap
                .map((params: Params) => params.params)
                .subscribe( (params) => {
                     if(params && params['test']){
                        let testQueryParamVal = params['test'];
                     }
                 });
  }
asmmahmud
  • 4,844
  • 2
  • 40
  • 47
  • yes this worked this.route.paramMap.subscribe(map => console.log("map",map.get("ordertype"))); But I am able to test with URL as http://localhost:4200/OrderMgmtComponent/red When I give like below, it shows error http://localhost:4200/OrderMgmtComponent?ordertype="red" ERROR: ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'OrderMgmtComponent' Error: Cannot match any routes. URL Segment: 'OrderMgmtComponent' Any idea why it show the error ? – aabbcc Oct 10 '17 at 05:45
  • You're getting this error because you've not defined that route with only `OrderMgmtComponent`. Be aware that in angular `route params` and `route query params` are two different things. – asmmahmud Oct 10 '17 at 07:04
  • Pls see this link https://github.com/angular/angular-cli/issues/6410 This says we cannot test URL with http://localhost:4200?a=b – aabbcc Oct 10 '17 at 10:26