我使用angular2.0.0-beta.7。当组件加载在/path?Query =value1它被重定向到/path。为什么GET参数被移除?如何保存参数?

我的路由器出错了。如果我有一条主干道

@RouteConfig([
  {
      path: '/todos/...',
      name: 'TodoMain',
      component: TodoMainComponent
  }
])

我的孩子就像

@RouteConfig([
  { path: '/', component: TodoListComponent, name: 'TodoList', useAsDefault:true },
  { path: '/:id', component: TodoDetailComponent, name:'TodoDetail' }
])

那么我就不能在TodoListComponent中获得参数。我所能得到的

params("/my/path;param1=value1;param2=value2") 

但我想要经典的

query params("/my/path?param1=value1&param2=value2")

当前回答

查询和路径(Angular 8)

如果你有像https://myapp.com/owner/123/show?height=23这样的url,那么使用

combineLatest( [this.route.paramMap, this.route.queryParamMap] )
  .subscribe( ([pathParams, queryParams]) => {
    let ownerId = pathParams.get('ownerId');    // =123
    let height  = queryParams.get('height');    // =height
    // ...
  })

更新

如果你使用this.router.navigate([yourUrl]);你的查询参数被嵌入到你的URL字符串中,然后angular对URL进行编码,你会得到类似https://myapp.com/owner/123/show%3Fheight%323的东西——以上解决方案会给出错误的结果(queryParams将为空,如果它在路径端,查询参数可以粘在last path param上)。在这种情况下,改变导航的方式

this.router.navigateByUrl(yourUrl);

其他回答

获取URL参数作为对象。

import { Router } from '@angular/router';
constructor(private router: Router) {
    console.log(router.parseUrl(router.url));
}

嗨,你可以使用URLSearchParams,你可以在这里阅读更多关于它。

进口:

import {URLSearchParams} from "@angular/http";

和功能:

getParam(){
  let params = new URLSearchParams(window.location.search);
  let someParam = params.get('someParam');
  return someParam;
}

注意:并非所有平台都支持它,angular文档似乎还处于“实验性”状态

当URL是这样的时候 http://stackoverflow.com?param1=value

你可以通过下面的代码得到参数1:

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

@Component({
    selector: '',
    templateUrl: './abc.html',
    styleUrls: ['./abc.less']
})
export class AbcComponent implements OnInit {
    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        // get param
        let param1 = this.route.snapshot.queryParams["param1"];
    }
}

您可以在URL中使用ActivatedRoute时获得查询参数,如下所示

url: http: / domain.com ?测试= abc

import { Component } from '@angular/core';
import { ActivatedRoute }     from '@angular/router';

@Component({
  selector: 'my-home'
})
export class HomeComponent {

  constructor(private sharedServices : SharedService,private route: ActivatedRoute) { 
    route.queryParams.subscribe(
      data => console.log('queryParams', data['test']));
  }

}

现在是:

this.activatedRoute.queryParams.subscribe((params: Params) => {
  console.log(params);
});