'Angular 7: How to access query string in URL from an iframe?
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?
Solution 1:[1]
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 #
Solution 2:[2]
You must subscribe to queryParams instead of params. See reference https://angular-2-training-book.rangle.io/handout/routing/query_params.html
Solution 3:[3]
This may help you somewhat
const firstParam: string = this.route.snapshot.params['id'];
Solution 4:[4]
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/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vipul Handa |
| Solution 2 | RoseHashmi |
| Solution 3 | Geethanjana Nallaperumage |
| Solution 4 | Binu |
