angular - 获取查询参数的角度路由定义
问题描述
我正在寻找应该匹配任何请求的路由定义,例如?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
?
这可以通过拦截路由过程来实现吗?
解决方案
对我来说,唯一真正可行的地方就是回家路线本身。'' 和 '**' 只是'重定向到 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) )
}
推荐阅读
- lua - Lua中的elseif和else if有什么区别?
- r - R:使用不同的子元素(每列的特定行)与 sapply
- swift - 如何进行正确的 API 调用?
- java - Javamail 没有收到所有邮件
- .htaccess - .htaccess 一些文件夹到子文件夹/文件夹
- docker - 在 docker 中运行时,将自签名证书添加到 Artifactory 中的 java 密钥库
- go - 匿名结构作为模板中的管道
- c# - 多个类之间共享的列表
- powershell - 输出一个字符串然后做一些事情并添加到同一个字符串
- android - SharedPreferences 变量只被接收并且可以在第二次执行时显示