Angular2 cannot use the values of a subscribe in another subscribe (observable)

徘徊边缘 提交于 2019-12-24 07:31:22

问题


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!

Code:

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);
              });
          }
      );
    }

回答1:


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

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();
}


来源:https://stackoverflow.com/questions/43831871/angular2-cannot-use-the-values-of-a-subscribe-in-another-subscribe-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!