我使用的是angular 5.0.3,我想用一堆查询参数启动我的应用程序,比如/app?param1=hallo&param2=123。如何在Angular 2中从url中获取查询参数?对我没用。

有什么想法如何获得查询参数工作?

private getQueryParameter(key: string): string {
  const parameters = new URLSearchParams(window.location.search);
  return parameters.get(key);
}

这个私有函数帮助我获取参数,但我认为在新的Angular环境中这不是正确的方式。

(更新:) 我的主应用程序是这样的

@Component({...})
export class AppComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    // would like to get query parameters here...
    // this.route...
  }
}

当前回答

简单的解决方案

 // in routing file
       {
            path: 'checkout/:cartId/:addressId',
            loadChildren: () => import('./pages/checkout/checkout.module').then(m => m.CheckoutPageModule)
          },

    // in Component file

            import { Router, ActivatedRoute } from '@angular/router';

                 constructor(
                      private _Router: ActivatedRoute
                  ) { }

                  ngOnInit() {
                    this.cartId = this._Router.snapshot.params.cartId;
                    this.addressId = this._Router.snapshot.params.addressId;
                    console.log(this.addressId, "addressId")
                    console.log(this.cartId, "cartId")
                  }

其他回答

父组件从ActivatedRoute获取空参数

对我有用:

import {Component, OnDestroy, OnInit} from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'app-navigation-bar',
  templateUrl: './navigation-bar.component.html',
  styleUrls: ['./navigation-bar.component.scss']
})
export class NavigationBarComponent implements OnInit, OnDestroy {
  private sub: any;
  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.sub = this.router.events.subscribe(val => {
      if (val instanceof RoutesRecognized) {
        console.log(val.state.root.firstChild.params);
      }
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

这对我很管用。我已经在路由模块中使用了子路由。


 this.route.firstChild.snapshot.paramMap.get('id');
   

你也可以使用HttpParams,比如:

  getParamValueQueryString( paramName ) {
    const url = window.location.href;
    let paramValue;
    if (url.includes('?')) {
      const httpParams = new HttpParams({ fromString: url.split('?')[1] });
      paramValue = httpParams.get(paramName);
    }
    return paramValue;
  }

小心你的路线。“redirectTo”将删除|删除任何查询参数。

const appRoutes: Routes [
 {path: "one", component: PageOneComponent},
 {path: "two", component: PageTwoComponent},
 {path: "", redirectTo: "/one", pathMatch: full},
 {path: "**", redirectTo: "/two"}
]

我用查询参数调用主组件,比如“/main?”param1=a&param2=b,并假设我的查询参数在重定向转发生效之前到达主组件中的“ngOnInit()”方法。

但这是错误的。重定向将出现在前面,删除查询参数并在没有查询参数的情况下调用主组件中的ngOnInit()方法。

我把第三条路线改成了

{path: "", component: PageOneComponent},

现在我的查询参数可以在主要组件ngOnInit和PageOneComponent中访问。

当你有一个空路由对象时,这主要是因为你没有在app.component.html中使用路由器出口。

如果没有这个,你将无法获得一个有意义的非空子对象的路由对象,特别是params和queryParams。

尝试添加<router-outlet><router-outlet> < app-main-component > < / app-main-component >

在此之前,确保你在App -routing >中准备好了查询参数,它导出了App组件使用的类Route:

param: '/param/:dynamicParam', path: MyMainComponent

当然,最后一件事,为了获得你的参数,我个人使用this.route.snapshot.params.dynamicParam,其中dynamicParam是在你的app-routing组件中使用的名称:)