【发布时间】:2017-05-15 14:08:20
【问题描述】:
在 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 事件(当我离开路线时发生)以取消订阅另一个订阅,即路由参数更改订阅哈哈...
我想这不是要走的路,但 Google 什么也没提供。
有人知道如何处理这种情况吗?还是应该路由参数更改订阅真的只属于一个组件?
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();
});
}
更新
当我将此代码放入 resolve 方法时:
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'],但为什么呢?
【问题讨论】:
-
我并不完全清楚问题是什么或您实际尝试完成什么。为什么你认为你需要退订?注入服务的路由器是根路由器,该路由器将在整个应用程序生命周期内保持不变。
-
我尝试完成:我想将 ngOnInit/ngOnDestroy 中的工作代码放入路由器解析类中,如果没有路由器解析类,行为应该是相同的。
-
我想使用解析功能,因为加载数据然后激活路由视图具有更好的最终用户体验。