我使用的是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...
  }
}

当前回答

它对我的作用是:

constructor(private route: ActivatedRoute) {}

ngOnInit()
{
    this.route.queryParams.subscribe(map => map);
    this.route.snapshot.queryParams; 
}

如何在angular2中从url获取查询参数?

其他回答

简单的解决方案

 // 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")
                  }

小心你的路线。“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中访问。

我认为是Angular 8:

ActivatedRoute。params已被ActivatedRoute.paramMap取代 ActivatedRoute。queryParams已被ActivatedRoute.queryParamMap取代

在Angular 5中,查询参数是通过订阅this.route.queryParams来访问的(注意,后面的Angular版本推荐queryParamMap,也可以查看其他答案)。

例如:/应用程序吗?param1 = hallo&param2 = 123

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    console.log('Called Constructor');
    this.route.queryParams.subscribe(params => {
        this.param1 = params['param1'];
        this.param2 = params['param2'];
    });
}

然而,路径变量是由this.route.snapshot.params访问的

操作:param1 / param1 param2 /: param2

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    this.param1 = this.route.snapshot.params.param1;
    this.param2 = this.route.snapshot.params.param2;
}

如果你没有使用Angular的router try, querystring。安装它

npm install --save querystring

对你的项目。在您的组件中执行如下操作

import * as qs from 'querystring';
...
ngOnInit() {
   const params = qs.parse(window.location.search.substring(1));
   ...
}

子字符串(1)是必要的,因为如果你有这样的'/mypage?Foo =bar'则键名为? Foo