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

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

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

代码:

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.internshipsundefined 因为这些调用是异步的,您可以获得更多信息

另请注意,您正在使用多个订阅,这不是一个好的做法,您应该使用一些 operators 来组合您的可观察对象,例如 switchMap mappluck

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