【发布时间】:2018-07-11 20:11:50
【问题描述】:
我的问题是关于 angular 4,如何获取路由参数,例如,如果用户使用而不是默认 url(例如 http://localhost:3000/)进入您的页面,而不是像 http://localhost:3000/user/:id 这样的东西,以及能够从该网址获取:id(用户直接在浏览器中输入,而不是通过应用程序导航)。
在下面的示例中使用了相同的组件,主要是因为需要捕获该 id 并调度其他操作,如果它存在,那就是它。
我尝试过使用ActivatedRoute,但据我所知,这仅在整个应用程序中导航时有效,从应用程序内部,而不是在这种情况下,如果该 url 总是返回一个空值直接在浏览器中输入,它会被重定向到默认的/ 路由,就是这样。
非常感谢任何提示或指示
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?
});
}
}
【问题讨论】:
-
将 RouteModule.forRoot() 直接导入 app.module 时会发生什么?
-
好吧,没什么,只是直接从那里使用路线,没有注意到任何问题或其他问题,应用程序本身比所提供的示例大得多,并且运行良好:)跨度>
标签: javascript angular angular4-router