如何从Angular 2中的url获取查询参数?

TypeScript

小宇宙

2020-06-02

我使用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")

第4243篇《如何从Angular 2中的url获取查询参数?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
武藏 2020.06.02

如果未在路由中定义参数,则无法从RouterState获取参数,因此在您的示例中,您必须解析查询字符串...

这是我使用的代码:

let re = /[?&]([^=#&]+)=([^&#]*)/g;
let match;
let isMatch = true;
let matches = [];
while (isMatch) {
    match = re.exec(window.location.href);
    if (match !== null) {
        matches[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
        if (match.index === re.lastIndex) {
            re.lastIndex++;
        }
    }
    else {
        isMatch = false;
    }
}
console.log(matches);

蓝染大人 2020.06.02

现在它是:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android