我一直在尝试按照本教程[使用 Angular 2 和 Firebase 构建应用程序][1]
学习 Angular 2,并尝试对其进行扩展。但是我在尝试嵌套多条路线时遇到了麻烦。
应用结构:
Goals – (has router-outlet)
> Single Goal with Experiments list – (has router-outlet)
> Single Experiment – (has router-outlet)
> Experiment Notes
路由器设置:
export const routerConfig : Route[] = [
{
path: 'goals',
children: [
{
path: ':id', component: SingleGoalComponent,
children: [
{
path: 'experiments',
children: [
{ path: ':id', component: ExperimentDetailsComponent,
children: [
{ path: '', redirectTo: 'notes', pathMatch: 'full' },
{ path: 'notes', component: ExperimentNotesComponent }
]
},
{ path: 'new', component: NewExperimentComponent },
{ path: '' }
]
},
{ path: '', redirectTo: 'experiments', pathMatch: 'full' }
]
},
{ path: '', component: GoalsComponent }
]
},
{ path: 'notes', component: NotesComponent },
{ path: '', redirectTo: 'goals', pathMatch: 'full' },
{ path: '**', redirectTo: 'goals', pathMatch: 'full' }
];
问题
如果我点击实验列表中的实验 1,我会到达 goals/1/experiments/1/notes
url 是正确的,我看到了正确的 实验 1 的笔记。
如果我然后点击实验列表中的实验 2 goals/1/experiments/2/notes
url 是正确的实验细节是正确的但注释是还是实验1的笔记。
如果我随后刷新浏览器,实验 2 将加载,笔记现在是实验 2 的笔记,这是正确的。
这就是我如何获取用于检索笔记的 experimentId
experiment-notes.component.ts
experimentId: string;
goalId: string;
constructor(
private router: Router,
private route: ActivatedRoute,
private experimentsService: ExperimentsService,
private _location: Location) { }
ngOnInit() {
Observable.combineLatest(this.route.parent.params, this.route.parent.parent.params)
.forEach((params: Params[]) => {
this.experimentId = params[0]['id'];
this.goalId = params[1]['id'];
});
console.log('Experiment ID: ' + this.experimentId + '| Goal Id: ' + this.goalId);
this.notes$ = this.experimentsService.findAllNotesForExperiment(this.experimentId);
我确定我犯了一个明显的错误,但就我的生活而言,我看不出我哪里出了问题。
最佳答案
这是因为 ngOnInit() 方法在创建组件期间仅调用一次。当您点击实验 2 时,您不会创建新的实验组件。你只用旧的。
Url 正在更改,因为您仍然订阅了路由参数。但是您的服务调用不在 Observable 范围内。所以只需将服务调用放入您的可观察对象中,然后每次更改路由参数时,它都会加载新数据。
ngOnInit() {
Observable.combineLatest(this.route.parent.params, this.route.parent.parent.params)
.forEach((params: Params[]) => {
this.experimentId = params[0]['id'];
this.goalId = params[1]['id'];
console.log('Experiment ID: ' + this.experimentId + '| Goal Id: ' + this.goalId);
this.notes$ = this.experimentsService.findAllNotesForExperiment(this.experimentId);
});
关于angular - 子组件不更新父路由更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548496/