【问题标题】:Angular2 cannot use the values of a subscribe in another subscribe (observable)Angular2 不能在另一个订阅中使用订阅的值(可观察)
【发布时间】:2017-10-05 12:35:50
【问题描述】:

我想在另一个订阅方法中使用一个值,但它给了我 undefined 因为它不是异步的。有没有一种方法可以一起使用这些值?我想在以下订阅方法中再次使用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);
              });
          }
      );
    }

【问题讨论】:

  • 所以你想合并两个 observables 的结果?使用Observable.combineLatest
  • 我只需要第二个中的第一个值是的。我现在正在查看 combineLatest 方法,但很难找到两个订阅方法。 @jonrsharpe
  • 你是什么意思“有两个订阅方法”?只是Observable.combineLatest(this._internshipAssignmentService.getInternshipAssignments(), this.router.params, (assignments, params) =&gt; { ... });

标签: angular service undefined observable angular2-services


【解决方案1】:

this.internshipsundefined 因为这些调用是异步的,你可以得到更多信息here

还请注意,您正在使用多个订阅,这不是一个好习惯,您应该使用一些 operators 组合您的 observable,例如 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();
}

【讨论】:

  • 谢谢,我在一个只有一次的项目中使用了 angular2,所以我真的不擅长。你给我的代码有效,现在我知道我不能使用多个订阅但使用 switchmaps。但它现在工作正常,谢谢!理解您的代码也需要一些时间,因为如果您不太了解功能,它会很复杂
  • 很高兴它有帮助。您可以查看rxjs docs 以了解可用的运算符。另外,看看主页上的小工具“我有一个可观察的......”这对于找到适合您想要实现的目标的运算符很有用。
猜你喜欢
  • 1970-01-01
  • 2019-07-10
  • 2021-06-14
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
相关资源
最近更新 更多