如何处理angular 2中的查询参数 [英] How to handle query parameters in angular 2

查看:27
本文介绍了如何处理angular 2中的查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的可路由组件中,我有

@RouteConfig {
  {path: '/login',   name: 'Login', component: LoginComponent}
}  

但是如果我去app_url/login?token=1234,我如何获得查询参数?

But how do I get the query params if I go to app_url/login?token=1234?

推荐答案

为了补充前面的两个答案,Angular2 支持路由中的查询参数和路径变量.在 @RouteConfig 定义中,如果您在路径中定义参数,Angular2 会将它们作为路径变量处理,否则作为查询参数处理.

To complement the two previous answers, Angular2 supports both query parameters and path variables within routing. In @RouteConfig definition, if you define parameters within a path, Angular2 handles them as path variables and as query parameters if not.

让我们举个例子:

@RouteConfig([
  { path: '/:id', component: DetailsComponent, name: 'Details'}
])

如果你像这样调用路由器的navigate方法:

If you call the navigate method of the router like this:

this.router.navigate( [
  'Details', { id: 'companyId', param1: 'value1'
}]);

您将拥有以下地址:/companyId?param1=value1.获取参数的方式对于查询参数和路径变量都是相同的.它们的区别在于路径变量可以看作是必选参数,查询参数可以看作是可选参数.

You will have the following address: /companyId?param1=value1. The way to get parameters is the same for both, query parameters and path variables. The difference between them is that path variables can be seen as mandatory parameters and query parameters as optional ones.

希望对你有帮助蒂埃里

更新:更改路由器 alpha.31 http 查询参数后不再有效(矩阵参数#2774).相反,角度路由器使用所谓的矩阵 URL 表示法.

UPDATE: After changes in router alpha.31 http query params no longer work (Matrix params #2774). Instead angular router uses so called Matrix URL notation.

参考 https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:

可选路由参数不以?"分隔和&"像他们将在 URL 查询字符串中.它们用分号;"隔开这是矩阵 URL 表示法 - 您以前可能没有见过.

The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.

这篇关于如何处理angular 2中的查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆