在ngOnDestroy方法中,我取消订阅我订阅的一个observable,否则代码会多次执行...
ngOnInit()
{
this.sub = this.route.params.subscribe(params =>
{
this.projectId = +params['id'];
this.projectStore.project = this.projectId;
// load data when the route changes
this._tasksService.gettasks(this.projectId).subscribe(years => { this.tasks = years.map(y => new task(y)) }); // no need to clean up the subscription
});
// load data when the component is initialized
this._tasksService.gettasks(this.projectId).subscribe(years => { this.tasks = years.map(y => new task(y)) }); // no need to clean up the subscription
}
ngOnDestroy()
{
this.sub.unsubscribe();
}
现在我想把它放在路由器解析类中,但是没有ngOnDestroy - 当然 - 只是一个我再次订阅的NavigationEnd事件。
这意味着我订阅了一个NavigationStart事件(当我离开路线时发生)以取消订阅另一个订阅,这是路由参数更改订阅HAHAHA ......
我想这不是可行的方法,但谷歌什么也没提供。
任何人都知道如何处理这种情况?或者应该路由params更改订阅真的只属于一个组件吗?
constructor(private service: TasksService, private router: Router)
{
this.navigationEnded = this.router.events
.filter(event => event instanceof NavigationStart)
.map(() => this.router.routerState.root)
.subscribe((event) =>
{
this.navigationEnded.unsubscribe();
});
}
更新
当我将此代码放入解析方法时:
this.route.params.subscribe(params =>
{
// reload data by the new id parameter does not work with params
// I have to use inside here: route.params['id']
});
params数组中没有id,它的长度为0。
相反,我必须在params订阅中使用route.params ['id'],但为什么呢?
答案 0 :(得分:5)
您可以使用first()
运算符。这样,observable在第一个事件之后完成。无需取消订阅:
this.router.events
.filter(event => event instanceof NavigationStart)
.map(() => this.router.routerState.root)
.first()
.subscribe((event) =>
{
//this.navigationEnded.unsubscribe();
});