从应用程序中直接输入的网址中读取路由参数
我的问题是关于角度4,如何获取路由参数,例如,如果用户进入您的页面,而不是默认网址(例如http://localhost:3000/
)到达http://localhost:3000/user/:id
之类的地址,并能够从该网址中获取:id
(用户已直接在浏览器中输入了:id
,而不是通过应用进行导航).
My question would be regarding angular 4, how to get route params, if for example a user gets on your page with, instead of the default url, like for example http://localhost:3000/
, to something like http://localhost:3000/user/:id
, and to be able to pick up the :id
from that url (user has directly entered it in the browser, not navigating through the app).
在下面的示例中,使用了相同的组件,主要是因为需要捕获该ID并调度其他操作(如果存在的话).
In the example bellow same component is used, mainly because of needing to catch that id and dispatch other actions, if its present, and that would be it.
我尝试使用ActivatedRoute
进行操作,但是到目前为止,这仅适用于从应用程序内部导航到整个应用程序的情况,而不是在这种情况下,如果该网址为,则始终返回null值直接在浏览器中输入,它将重定向到默认的/
路由,就是这样.
I have tried playing around with ActivatedRoute
but from what I could tell so far, that only works when navigation throughout the app, from within the app, not in this case, which always returns a null value if that url is directly entered in the browser, it gets redirected to the default /
route and that would be it.
任何提示或指示都将不胜感激
Any tips or pointers are much appreciated
app.routing-module.ts
app.routing-module.ts
import {hookComponent} from './hook.component';
import {RouterModule, Routes} from '@angular/router';
import {NgModule} from '@angular/core';
export const routes: Routes = [
{
path: '',
component: HookComponent
},
{
path: 'user/:id',
component: HookComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, { enableTracing: true })],
exports: [RouterModule]
})
export class AppRoutingModule {}
hook.component
hook.component
import {Component, EventEmitter, Input, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, ParamMap} from '@angular/router';
@Component({
selector: 'hook',
templateUrl: 'hook.component.html',
styleUrls: ['hook.component.scss']
})
export class HookComponent implements OnDestroy, OnInit {
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
console.log('params are', params); //null?
});
}
}
您的方法已经可以了,但是在您的示例中,params
是一个数组,您可以通过调用params['id']
来访问:id
:
Your way is already ok, but in your example params
is an array and you can access to :id
by calling params['id']
:
this.sub = this.route.params.subscribe(params => {
console.log('params are', params['id']);
});
此处是stackblitz上的一个有效示例.
Here is an working example on stackblitz.