我已经看过几个例子,但我似乎无法获得params可观察工作的订阅功能。我能够使router.events工作。我究竟做错了什么?基于路径参数变化的角度4重载路由
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { ProjectService } from '../../services/project.service';
import { Project } from "../../domain/project";
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html'
})
export class NavBarComponent implements OnInit {
projects: Project[] = [];
constructor(private projectService: ProjectService,
private route : ActivatedRoute,
private router : Router) {
this.projectService.getProjects();
}
ngOnInit() {
this.projectService.projectsChange.subscribe(result => {
this.projects = result;
});
this.projectService.projectChange.subscribe(result => {
this.projectService.getProjects();
});
// This only works the first time the component is routed to
this.activatedRoute.params.subscribe(params => {
console.log(params);
console.log("did this work at all?");
this.projectService.getProject(params['id']);
});
// This works when the param changes in the router
this.router.events.subscribe((val) => {
console.log(this.router.url);
let url = this.router.url;
let id = url.substring(url.length - 2, url.length);
this.projectService.getProject(Number(id));
});
}
}
这是路线(孩子)
{ path: '', component: DashboardComponent, canActivate: [AuthenticationGuard],
children: [
{ path: 'projects/:id', component: ProjectComponent }
]
}
这是链接如何模板
[routerLink]="['/projects/', project.id]"
您是否在使用this.activatedRoute.params.subscribe时遇到错误? – LLai
没有错误,只是NavigationStart,RoutesRecognized和NavigationEnd与正确的网址。 – Grim
嗯,你可以发布一些更多的component.ts代码吗? (构造函数,activatedRoute导入等)您是否在构造函数或ngOnInit生命周期钩子中订阅? – LLai