【问题标题】:Angular 7: How to access query string in URL from an iframe?Angular 7:如何从 iframe 访问 URL 中的查询字符串?
【发布时间】:2019-05-12 02:38:12
【问题描述】:

正在开发的应用托管在 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 { }

在ListComponent、OnInit方法中,我使用了以下代码来获取查询字符串参数:

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

QueryParamMap 或 RoutesRecongnized 似乎没有在 url 中获取查询字符串“id=3”。它总是返回 null。

谁能帮助我如何从 Angular 应用程序中的 url 检索查询参数/查询字符串?

【问题讨论】:

  • 你是把参数加到 iFrame url 还是主机 url 上?如果您没有尝试将参数传递给 iFrame。
  • 您的应用程序的完整 iframe URL 是什么?

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


【解决方案1】:

由于应用程序位于 iframe 下。而不是去快照你应该使用 subscribe 方法来获取参数。同时检查 fragment 是否得到你 # 之后的完整网址

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这可能对你有所帮助

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

      【讨论】:

        【解决方案4】:

        您需要通过订阅阅读或使用 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/

        【讨论】:

          猜你喜欢
          • 2019-09-18
          • 2019-02-27
          • 1970-01-01
          • 2020-05-10
          • 2014-09-04
          • 2014-05-30
          • 1970-01-01
          • 2018-12-08
          • 2019-01-14
          相关资源
          最近更新 更多