Get URL Params in Angular 7/8 App Component

I have setup Single Sign On (SSO) for my app, but I also need to be able to read values from URL parameters (localhost:4200/?id=test&name=testing&email=testing@test.com) and pass them to an API in the App Component.

A flag (url_enabled) will determine whether to read from the URL or use the SSO function.

In the App Component, I have tried to get the URL parameters using queryParams, params, url, queryParamsMap, but none of these seem to be working - I only get empty values.

The code in my App Component is as follows:

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 the solutions I have found from Stack Overflow and other blogs, but haven’t been able to figure out what I am missing. Can someone please suggest a solution?

You need to move the this.route.queryParams.subscribe() code inside the NavigationEnd event handler to make sure you only try to read the parameters after the navigation has ended. Also, you need to check the url_enabled flag to determine whether to read from the URL or use the SSO function. Here’s the updated code:

app.component.ts

import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';

constructor(private router: Router, private route: ActivatedRoute) {}

ngOnInit() {
  this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd)
  ).subscribe(() => {
    if (this.url_enabled) {
      const queryParams = this.route.snapshot.queryParams;
      console.log(queryParams.id, queryParams.name, queryParams.email);
      // Call API with queryParams values
    } else {
      // Call SSO function
    }
  });
}
app.component.html

<router-outlet></router-outlet>
app-routing.module.ts

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

Note: You also need to remove the * from the path in your app-routing.module.ts file so that it matches the empty path.