6

正在开发的应用程序托管在 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 检索查询参数/查询字符串?

4

4 回答 4

0

这可能会对您有所帮助

const firstParam: string = this.route.snapshot.params['id'];
于 2019-01-04T17:58:46.490 回答
0

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

于 2019-01-04T11:28:17.670 回答
0

由于该应用程序位于 iframe 下。而不是去快照,你应该使用订阅方法来获取参数。还要检查片段是否在 # 之后为你提供完整的 url

于 2019-01-03T10:30:01.003 回答
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/

于 2019-01-04T18:26:39.723 回答