Javascript 如何处理angular 2中的查询参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34599174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle query parameters in angular 2
提问by monty_lennie
In my routable component
I have
在我的routable component
我有
@RouteConfig {
{path: '/login', name: 'Login', component: LoginComponent}
}
But how do I get the query params if I go to app_url/login?token=1234
?
但是如果我去,我如何获得查询参数app_url/login?token=1234
?
采纳答案by Thierry Templier
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.
为了补充前面的两个答案,Angular2 支持路由中的查询参数和路径变量。在@RouteConfig
定义中,如果您在路径中定义参数,Angular2 会将它们作为路径变量处理,否则作为查询参数处理。
Let's take a sample:
让我们举个例子:
@RouteConfig([
{ path: '/:id', component: DetailsComponent, name: 'Details'}
])
If you call the navigate
method of the router like this:
如果你navigate
像这样调用路由器的方法:
this.router.navigate( [
'Details', { id: '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.
您将拥有以下地址:/companyId?param1=value1
. 获取参数的方式对于查询参数和路径变量都是相同的。它们之间的区别在于,路径变量可以看作是必选参数,而查询参数可以看作是可选参数。
Hope it helps you, Thierry
希望对你有帮助,蒂埃里
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.
更新:更改路由器 alpha.31 http 查询参数后不再工作(矩阵参数 #2774)。相反,角度路由器使用所谓的矩阵 URL 表示法。
Reference https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:
参考https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:
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.
可选的路由参数不以“?”分隔 和“&”,因为它们将出现在 URL 查询字符串中。它们用分号“;”隔开 这是矩阵 URL 表示法 - 您可能以前从未见过。
回答by Jayantha Lal Sirisena
RouteParams are now deprecated , So here is how to do it in the new router.
RouteParams 现在已弃用,所以这里是如何在新路由器中执行此操作。
this.router.navigate(['/login'],{ queryParams: { token:'1234'}})
And then in the login component you can take the parameter,
然后在登录组件中,您可以采用参数,
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.queryParams['token']
}
Hereis the documentation
这是文档
回答by Stephen
It seems that RouteParams
no longer exists, and is replaced by ActivatedRoute
. ActivatedRoute
gives us access to the matrix URL notation Parameters. If we want to get Query string ?
paramaters we need to use Router.RouterState
. The traditional query string paramatersare persisted across routing, which may not be the desired result.Preserving the fragment is now optional in router 3.0.0-rc.1.
似乎RouteParams
不再存在,取而代之的是ActivatedRoute
。ActivatedRoute
使我们可以访问矩阵 URL 符号参数。如果我们想获取查询字符串?
参数,我们需要使用Router.RouterState
. 在传统的查询字符串PARAMATERS跨路由,这可能不是所希望的结果仍然存在。保留片段现在在路由器 3.0.0-rc.1 中是可选的。
import { Router, ActivatedRoute } from '@angular/router';
@Component ({...})
export class paramaterDemo {
private queryParamaterValue: string;
private matrixParamaterValue: string;
private querySub: any;
private matrixSub: any;
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.router.routerState.snapshot.queryParams["queryParamaterName"];
this.querySub = this.router.routerState.queryParams.subscribe(queryParams =>
this.queryParamaterValue = queryParams["queryParameterName"];
);
this.route.snapshot.params["matrixParameterName"];
this.route.params.subscribe(matrixParams =>
this.matrixParamterValue = matrixParams["matrixParameterName"];
);
}
ngOnDestroy() {
if (this.querySub) {
this.querySub.unsubscribe();
}
if (this.matrixSub) {
this.matrixSub.unsubscribe();
}
}
}
We should be able to manipulate the ?
notation upon navigation, as well as the ;
notation, but I only gotten the matrix notation to work yet. The plnkerthat is attached to the latest router documentationshows it should look like this.
我们应该能够?
在导航时操纵符号以及;
符号,但我只让矩阵符号起作用。附加到最新路由器文档的plnker显示它应该如下所示。
let sessionId = 123456789;
let navigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
回答by brando
This worked for me (as of Angular 2.1.0):
这对我有用(从 Angular 2.1.0 开始):
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.snapshot.queryParams['token']
}
回答by marcel
Angular2 v2.1.0(stable):
Angular2 v2.1.0(稳定版):
The ActivatedRoute provides an observable one can subscribe.
ActivatedRoute 提供了一个可以订阅的 observable。
constructor(
private route: ActivatedRoute
) { }
this.route.params.subscribe(params => {
let value = params[key];
});
This triggers everytime the route gets updated, as well: /home/files/123 -> /home/files/321
每次更新路由时也会触发:/home/files/123 -> /home/files/321
回答by Wetteren Rémi
(For Childs Route Only such as /hello-world)
(仅限 Childs Route,例如 /hello-world)
In the case you would like to make this kind of call :
如果您想拨打此类电话:
/hello-world?foo=bar&fruit=banana
/hello-world?foo=bar&fruit=banana
Angular2 doesn't use ?nor &but ;instead. So the correct URL should be :
Angular2 不使用? 也不是&但是; 反而。所以正确的网址应该是:
/hello-world;foo=bar;fruit=banana
/hello-world;foo=bar;fruit=banana
And to get those data :
并获取这些数据:
import { Router, ActivatedRoute, Params } from '@angular/router';
private foo: string;
private fruit: string;
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.foo = params['foo'];
this.fruit = params['fruit'];
});
console.log(this.foo, this.fruit); // you should get your parameters here
}
Source : https://angular.io/docs/ts/latest/guide/router.html
回答by Ally
Angular 4:
角度 4:
I have included JS (for OG's) and TS versions below.
我在下面包含了 JS(用于 OG)和 TS 版本。
.html
.html
<a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>
In the above I am using the link parameter arraysee sources below for more information.
在上面我使用链接参数数组,请参阅下面的来源以获取更多信息。
routing.js
路由.js
(function(app) {
app.routing = ng.router.RouterModule.forRoot([
{ path: '', component: indexComponent },
{ path: 'search', component: searchComponent }
]);
})(window.app || (window.app = {}));
searchComponent.js
搜索组件.js
(function(app) {
app.searchComponent =
ng.core.Component({
selector: 'search',
templateUrl: 'view/search.html'
})
.Class({
constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
// Pull out the params with activatedRoute...
console.log(' params', activatedRoute.snapshot.params);
// Object {tag: "fish"}
}]
}
});
})(window.app || (window.app = {}));
routing.ts (excerpt)
routing.ts(摘录)
const appRoutes: Routes = [
{ path: '', component: IndexComponent },
{ path: 'search', component: SearchComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
// other imports here
],
...
})
export class AppModule { }
searchComponent.ts
搜索组件.ts
import 'rxjs/add/operator/switchMap';
import { OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
export class SearchComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params
.switchMap((params: Params) => doSomething(params['tag']))
}
More infos:
更多信息:
"Link Parameter Array" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
“链接参数数组” https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
"Activated Route - the one stop shop for route info" https://angular.io/docs/ts/latest/guide/router.html#!#activated-route
“激活路线 - 路线信息的一站式商店” https://angular.io/docs/ts/latest/guide/router.html#!#activated-route
回答by Amir
For Angular 4
对于 Angular 4
Url:
网址:
http://example.com/company/100
Router Path :
路由器路径:
const routes: Routes = [
{ path: 'company/:companyId', component: CompanyDetailsComponent},
]
Component:
成分:
@Component({
selector: 'company-details',
templateUrl: './company.details.component.html',
styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
companyId: string;
constructor(private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.companyId = params.companyId;
console.log('companyId :'+this.companyId);
});
}
}
Console Output:
控制台输出:
companyId : 100
公司编号:100
回答by William Hampshire
Angular 5+ Update
Angular 5+ 更新
The route.snapshot provides the initial value of the route parameter map. You can access the parameters directly without subscribing or adding observable operators. It's much simpler to write and read:
route.snapshot 提供路由参数映射的初始值。您可以直接访问参数,而无需订阅或添加可观察的运算符。写和读要简单得多:
Quote from the Angular Docs
To break it down for you, here is how to do it with the new router:
为您分解,以下是使用新路由器的方法:
this.router.navigate(['/login'], { queryParams: { token:'1234'} });
And then in the login component (notice the new .snapshot
added):
然后在登录组件中(注意新.snapshot
添加的):
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sessionId = this.route.snapshot.queryParams['token']
}
回答by Andrew
In Angular 6, I found this simpler way:
在 Angular 6 中,我发现了这种更简单的方法:
navigate(["/yourpage", { "someParamName": "paramValue"}]);
Then in the constructor or in ngInit
you can directly use:
然后在构造函数中或者在ngInit
你可以直接使用:
let value = this.route.snapshot.params.someParamName;