Angular 7:如何从iframe访问URL中的查询字符串?

时间:2018-12-11 06:21:44

标签: angular angular7 query-parameters angular-cli-v7

正在开发的应用托管在iframe中。

我在我的应用中配置了以下路由:

    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 { }

ListComponentOnInit方法中,我使用以下代码获取查询字符串参数:

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');

这些似乎都不起作用。 我为我的应用程序提供的网址如下:

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

QueryParamMapRoutesRecongnized似乎在URL中未获得查询字符串“ id = 3”。它总是返回null。

有人可以帮助我如何从angular应用程序的url中检索查询参数/查询字符串吗?

4 个答案:

答案 0 :(得分:0)

该应用位于iframe下。而不是去快照你应该使用    订阅方法以获取参数。还要检查片段是否能找到您    #

之后的完整网址

答案 1 :(得分:0)

您必须订阅 queryParams 而不是params。参见参考文献https://angular-2-training-book.rangle.io/handout/routing/query_params.html

答案 2 :(得分:0)

这可能会对您有所帮助

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

答案 3 :(得分:0)

您需要通过订阅阅读或使用Rxjs而不是快照

下面是示例:

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
        });
    });
} 

浏览Rxjs实现的链接。链接:https://kamranahmed.info/blog/2018/02/28/dealing-with-route-params-in-angular-5/