Angular2不能在另一个订阅中使用一个订阅的值(可观察)

编程入门 行业动态 更新时间:2024-10-18 23:27:18
本文介绍了Angular2不能在另一个订阅中使用一个订阅的值(可观察)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在另一个方法中使用订阅方法中的值,但是它给我未定义的信息,因为它不是异步的.有没有一种方法可以将这些值一起使用?我想在下面的订阅方法中再次使用this.internships,但是它变得不确定.谢谢您的帮助!

I wanted to use a value from a subscribe method in another one, but it gives me undefined because it is not async. Is there a method to use those values together? I want to use this.internships another time in the following subscribe method but it becomes undefined. Thank you for helping!

代码:

ngOnInit(): void { this._internshipAssignmentService.getInternshipAssignments() .subscribe(internships => { this.internships = internships; <---- value which gives an object this.internshipsHelper = internships; console.log(this.internships)}, error => this.msgs.push({ severity: 'error', summary: 'Error', detail: 'Er is een onverwachte fout opgetreden.' })); this.sub = this._route.params.subscribe( params => { let id = +params['id']; this._internshipAssignmentService.getAllFavorites() .subscribe(f => { this.favorites = f; this.favorite = this.getFavoritesFromIdStudent(1); console.log(this.internships); <----- value which gives undefined this.getFavorites(this.favorite); }); } ); }

推荐答案

this.internships是undefined,因为这些调用是异步的,所以您可以获得更多信息此处.

this.internships is undefined because these calls are asynchronous, you can get more informations here.

还请注意,您正在使用多个订阅,这不是一个好习惯,您应该使用一些操作符(例如switchMap map,pluck等)

Also note that you are using multiple subscription, which is not a good practice, you should combine your observable using some operators like switchMap map,pluck, etc.

ngOnInit(): void { this.sub = this._internshipAssignmentService.getInternshipAssignments().do((internships) => { this.internships = internships; // not needed if you just use it in next callbacks this.internshipsHelper = internships; console.log(this.internships) }).catch(error => { this.msgs.push({ severity: 'error', summary: 'Error', detail: 'Er is een onverwachte fout opgetreden.' }) }).switchMap(internships => this._route.params.pluck('id').switchMap(id => { return this._internshipAssignmentService.getAllFavorites().do(f => { this.favorites = f; this.favorite = this.getFavoritesFromIdStudent(1); this.getFavorites(this.favorite); }) })) .subscribe(); }

更多推荐

Angular2不能在另一个订阅中使用一个订阅的值(可观察)

本文发布于:2023-11-27 23:33:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!