Search code examples
angularangular-routerquery-string

Angular2: Accessing query parameters from URL giving error


Am trying to extract query parameters from the url

https://localhost:8080/myapp/shared?id1=2&id2=4

I need to use id1 and id2 values in my app.component.ts. Am trying to use Router, ActivatedRoute, Params from '@angular/router' but when I run the application, the main page is not loaded and I see the following error in browser console:

Error: StaticInjectorError[t]: 
 StaticInjectorError[t]: 
   NullInjectorError: No provider for t!
Stack trace:


LMZF/</yi</t.prototype.get@http://localhost:8081/myapp/main.a7059837ce4dd4ad4d9f.bundle.js:1:293926
y/<@http://localhost:8081/myapp/main.a7059837ce4dd4ad4d9f.bundle.js:1:237630
y@http://localhost:8081/myapp/main.a7059837ce4dd4ad4d9f.bundle.js:1:237237

And here is what my app.component.ts looks like:

import { Component, Input, OnInit } from '@angular/core';
import { HeaderComponent } from './header/header.component';
import {Router, ActivatedRoute, Params} from '@angular/router'; //added this import statement

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
  })

export class AppComponent implements OnInit {

constructor(private activatedRoute: ActivatedRoute) {}
// added following code for query params
ngOnInit() {
  // subscribe to router event
 this.activatedRoute.params.subscribe((params: Params) => {
     let userId = params['id1'];
     console.log("parameter is: "+ userId);
    });
}


   title = 'My First Angular App';
}

The thing is, i have added Router code which is causing the error without even loading the above url. As I try to run the application without the query param code, it runs fine.

Have tried this solution from this answer. Have also looked into another similar question but it didn't help.

Can someone explains why is that happening?

UPDATE

Have added following import statement in app.module.ts:

imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot([{
            path: '',
            component: AppComponent
        },
])

Now, this makes application load but still the parameters are not extracted. It is giving following error on browser console:

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'shared'

UPDATE 2

Adding route path for respective url solves the console error problem but still my parameter is undefined.

RouterModule.forRoot([{
        path: '',
        component: AppComponent
    },
    {
        path: 'shared',
        component: AppComponent
    },

])

Solution

  • You are accessing the route parameters specified in the routing module, for example /user/:uid. For the query params:

    export class AppComponent implements OnInit {
    
    constructor(private activatedRoute: ActivatedRoute) {}
    // added following code for query params
    ngOnInit() {
      // subscribe to router event
     this.activatedRoute.queryParams.subscribe((params: Params) => {
         let userId = params['id1'];
         console.log("parameter is: "+ userId);
        });
    }
    

    You could also use the ActivatedRouteSnapshot:

    import { ActivatedRouteSnapshot } from '@angular/router';
    
    export class AppComponent implements OnInit {
    
    constructor(private route: ActivatedRouteSnapshot) {}
    // added following code for query params
    ngOnInit() {
         console.log("all parameters: ", this.route.queryParamMap.getAll);
    }