angular – 如何取消订阅路径解析类中的observable
发布时间:2020-12-17 17:36:00 所属栏目:安全 来源:网络整理
导读:在ngOnDestroy方法中,我取消订阅我订阅的一个observable,否则代码被多次执行… ngOnInit(){ this.sub = this.route.params.subscribe(params = { this.projectId = +params['id']; this.projectStore.project = this.projectId; // load data when the route
在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(); }); } UPDATE 当我将此代码放入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’],但为什么呢? 解决方法
你可以使用first()运算符.这样,observable在第一个事件之后完成.无需取消订阅:
this.router.events .filter(event => event instanceof NavigationStart) .map(() => this.router.routerState.root) .first() .subscribe((event) => { //this.navigationEnded.unsubscribe(); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |