首页 > 解决方案 > 获取查询参数的角度路由定义

问题描述

我正在寻找应该匹配任何请求的路由定义,例如?p=%20some%random%20query. 我目前对路线的定义:

const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'blog/:title', component: BlogComponent },
{ path: '**', pathMatch: 'full', component: HomeComponent },];

p我的想法是使用{ path: '**', pathMatch: 'full', component: HomeComponent }和获取查询参数

 ngOnInit() {
     let id = this.route.snapshot.paramMap.get('p');
 }

. 但似乎 angular 只支持结构为 /:a/:b 的查询。例如查询http://localhost:4200?p=yoyoyo将被转换为http://localhost:4200/yoyoyo。相同的结果http://localhost:4200/?p=/blog/Add%20Token将被转换为http://localhost:4200/blog/Add%20Token. 因此,我无法检索查询参数的值p。如何制作一条适用的路线p=%以及如何检索 的值p

这可以通过拦截路由过程来实现吗?

标签: angularangular7

解决方案


对我来说,唯一真正可行的地方就是回家路线本身。'' 和 '**' 只是'重定向到 homecomponent

const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'blog/:title', component: BlogComponent },
{ path: '**', pathMatch: 'full', redirectTo: 'home' },];

在 homecomponent 中,您需要订阅以获取更改

constructor(private route: ActivatedRoute) {}
ngOnInit() {
    this.route.queryParams.subscribe(value => console.log(value) )

}

推荐阅读