Angular 7/8 - How to get url parameters in app component

Lovika picture Lovika · Jan 7, 2020 · Viewed 12.9k times · Source

I have Single sign on in place but for testing I want to read the values from the url localhost:4200/?id=test&name=testing&[email protected] and pass them to an API in app component.

there will be a flag on which basis I will reading from url instead of using single sign on function

if (url_enabled == true) {
    getParamsFromUrl()
 } else {
   singleSignOn()
 }

I tried ActivatedRoute but it doesn't seem to be working.

I have tried queryParams, params, url, queryParamsMap but none of these seems to be working. all I get is empty value.

inside app component

app.component.ts

 getParamsFromUrl() {
    this._router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        console.log(e.url)
      }
    })
  }

 this.route.queryParams.subscribe(params => {
      console.log(params);
    })

app.component.html

<router-outlet></router-outlet>

app-routing.module.ts

const routes: Routes = [
  {path:'*/:id', component: AppComponent},
];

I have tried whatever I could found on stackoverflow or other blogs. Can somebody point out what am I missing here?

Answer

Imranmadbar picture Imranmadbar · Jan 7, 2020

For this route: You can try this way:

const routes: Routes = [
   {path:'*/:id', component: AppComponent},
];   

In AppComponent .ts file:

    constructor(
      private activatedRoute: ActivatedRoute,
    ) { }




    ngOnInit() {
      this.activatedRoute.params.subscribe(params => {
          const id = params['id'];
          console.log('Url Id: ',id);
    }

    OR

    ngOnInit() {
      this.activatedRoute.queryParams.subscribe(params => {
          const id = +params.id;
          if (id && id > 0) {
           console.log(id);
          }
      });
    }