我有一个棱角分明的应用程序,我在网址task / 0中,并且我想导航到task / 1,tasks / 2等。
在task.component.html中,我有一个普通按钮:
<a (click)="onNext()">
Next
</a>
我显示一些有关任务的信息:
<div class="task-wrapper">
<div class="task-name">Name: {{ task.name }}</div>
<div class="task-description">Description: {{ task.description }}</div>
</div>
我导航到要去的地方(下一个任务ID)
task.component.ts
onNext() {
this.router.navigate(['../', this.currentTaskId + 1], {relativeTo: this.route});
}
这是有效的,因为网址已更改。
不幸的是,数据没有改变。我订阅了params的更改:
task.component.ts
this.route.params
.subscribe(
(params: Params) => {
this.currentTaskId = +params.taskId;
this.hackId = +params.hackId;
}
)
我已经将console.logs放在ngOnInit中,除非我刷新页面,否则它们永远不会被触发。如果刷新页面,则我具有正确的taskId(它已经在url中),并且可以看到正确的数据。
有帮助吗?
完整组件:
export class TaskDetailComponent implements OnInit {
task: Task;
currentTaskId: number;
hack: Hack;
hackId: number;
isLastTask: boolean = false;
isFirstTask: boolean = false;
isVisitor: boolean = false;
constructor(
private route: ActivatedRoute,
private router: Router,
private hackService: HackService,
private authService: AuthService
) { }
ngOnInit() {
console.log("ngOnInit aaaa")
this.task = new Task({
name: "",
description: ""
})
this.hack = new Hack({});
// in case refreshing
this.route.params
.subscribe(
(params: Params) => {
this.currentTaskId = +params.taskId;
this.hackId = +params.hackId;
this.hackService.hacksChanged.subscribe(
hacks => {
this.loadinfo(this.hackId, this.currentTaskId);
}
);
}
)
// navigating from inside the app, not refreshing
this.currentTaskId = +this.route.snapshot.params.taskId;
console.log(this.currentTaskId);
this.hackId = +this.route.snapshot.params.hackId;
const hacks = this.hackService.getHacks();
if (hacks) {
this.loadinfo(this.hackId, this.currentTaskId);
}
}
onNext() {
this.router.navigate(['../', this.currentTaskId + 1], {relativeTo: this.route});
}
loadinfo(hackId: number, currentTaskId: number) {
this.hack = this.hackService.getHack(this.hackId);
this.task = this.hack.tasks[this.currentTaskId];
const tasksLength = this.hack.tasks.length;
this.isLastTask = this.currentTaskId === tasksLength - 1
this.isFirstTask = this.currentTaskId === 0
// check if user is visitor
const loggedUserId = this.authService.getUid();
const creatorUserId = this.route.snapshot.params.userId;
this.isVisitor = creatorUserId !== loggedUserId
}
}
答案 0 :(得分:2)
我只能假定您正在获取onInit()
中的数据
您必须在params订阅上这样做
this.route.params
.subscribe(
(params: Params) => {
this.currentTaskId = +params.taskId;
this.hackId = +params.hackId;
//invoke data fetch here insteed of onInit
fetchDataLikeInOnInitYouDo()
}
)