我的问题是关于角度 4,如何获取路由参数,例如,如果用户使用默认 url 而不是默认 url(例如 http://localhost:3000/
(进入您的页面,例如 http://localhost:3000/user/:id
之类的东西,并且能够从该 URL 中获取:id
(用户直接在浏览器中输入它, 不浏览应用程序(。
在下面的示例中,使用了相同的组件,主要是因为需要捕获该 id 并调度其他操作(如果存在(,那就是它。
我尝试过使用ActivatedRoute
但据我目前所知,这仅在从应用程序内导航整个应用程序时才有效,在这种情况下不行,如果直接在浏览器中输入该 url,它总是返回一个 null 值,它被重定向到默认的/
路由,就是这样。
任何提示或指示都非常感谢
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 {}
钩子组件
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
:
this.sub = this.route.params.subscribe(params => {
console.log('params are', params['id']);
});
这是一个关于堆栈闪电战的工作示例。
通过Location
访问当前url
public constructor(location:Location) {
let url = location.prepareExternalUrl(location.path());
}
并从中解析出id
。
如果你只想记录params.id
;尝试像这样使用ActivatedRouteSnapshot
。
ngOnInit() {
console.log(this.route.snapshot.params.id);
}
如果要检查params.id
是否存在,可以执行以下操作:
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 {
hasId: boolean = false;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
if(this.route.snapshot.params.id !== null)
{
// do magic....
}
}
}