Angular 7: How to access query string in URL from an iframe?

8.3k Views Asked by At

The app under development is hosted within an iframe.

I have the following routes configured in my app:

    const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'list'
  },
  {
    path: 'list',
    component: ListComponent,
    canActivate: [CanActivateRoute]
  },
  {
    path: 'dashboard',
    loadChildren: './modules/dashboard/dashboard.module#DashboardModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { enableTracing: true })],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

In the ListComponent, OnInit method, I have used the following code to get query string params:

this.router.events.subscribe(val => {
      if (val instanceof RoutesRecognized) {
        console.log("val.state.root.firstChild.params: " + val.state.root.firstChild.params);
      }
    }); 
const firstParam: string = this.route.snapshot.queryParamMap.get('id');

None of these seem to work. The url I have for my application is as follows:

https://company.com/#/app-dev/list?id=3

QueryParamMap or RoutesRecongnized doesn't seem to get the query string "id=3" in the url. It always returns null.

Can anyone help me how to retrieve the query params / query string from url in angular app?

4

There are 4 best solutions below

0
On

You must subscribe to queryParams instead of params. See reference https://angular-2-training-book.rangle.io/handout/routing/query_params.html

0
On

This may help you somewhat

const firstParam: string = this.route.snapshot.params['id'];
0
On

As the app is under iframe . Rather then going for snapshot you should use subscribe method to fetch the params .Also check if the fragment gets you full url after #

0
On

Instead of snapshot, you need to read via Subscriptions or use Rxjs

Below is the example:

import { ActivatedRoute } from '@angular/router';

export class YourComponent implements OnInit {
    constructor(private activeRoute: ActivatedRoute) {
    }

    ngOnInit() {

    this.activeRoute.queryParams.subscribe(queryParams => {
        this.activeRoute.params.subscribe(routeParams => {
            //you will get query string here
        });
    });
} 

Go through the link for Rxjs implementation. Link: https://kamranahmed.info/blog/2018/02/28/dealing-with-route-params-in-angular-5/