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

4

6

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?

Astrogate answered 11/12, 2018 at 6:21 Comment(2)
Did you add the parameters to the iFrame url or to the host url? If you didn't try passing the parameters to the iFrame.Dimitri
What is the full iframe URL for your application?Garvey
D
0

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 #

Dehisce answered 3/1, 2019 at 10:30 Comment(0)
P
0

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

Peers answered 4/1, 2019 at 11:28 Comment(0)
G
0

This may help you somewhat

const firstParam: string = this.route.snapshot.params['id'];
Gesticulation answered 4/1, 2019 at 17:58 Comment(0)
Q
0

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/

Quartern answered 4/1, 2019 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.