【问题标题】:Angular wait until subscribe is done and give values to other functionAngular 等到订阅完成并为其他函数赋值
【发布时间】:2020-05-02 07:42:06
【问题描述】:

我有这个功能

文件:subcategory.service.ts

getSubCategoriesById(inp_subCatid: String): Observable<any>{
  this.getSubCategoriesList().snapshotChanges().pipe(
    map(changes =>
     changes.map(c =>
      ({ key: c.payload.key, ...c.payload.val() })
     )
    )
  ).subscribe(subCategories => {
    subCategories.filter(function (subCat) {
     return subCat.id == inp_subCatid;
   });
});

我正在调用以下文件中的顶部函数

文件:subcategory.page.ts

this.SubCategoryService.getSubCategoriesById(subCatid).subscribe((subCategories: any) => {
  this.subCat = subCategories ;
})

我得到的问题是我收到以下错误消息: 错误类型错误:“this.SubCategoryService.getSubCategorysById(...) 未定义”

我想在从文件“subcategory.service.ts”加载数据时获取数据 希望有人可以帮助我。

【问题讨论】:

  • 如果你想在其他地方订阅,你不能在getSubCategories内订阅。不订阅就直接退回

标签: javascript angular asynchronous subscribe


【解决方案1】:

你的方法应该是这样的:

getSubCategories(inp_subCatid: string): Observable<any> {
  return this.getSubCategoriesList().snapshotChanges().pipe(
    map(changes => changes.map(c => 
        ({ key: c.payload.key, ...c.payload.val() })
      ).filter((subCat) => subCat.id === inp_subCatid)
    ));
}

那么你就可以这样使用了:

this.subCategoryService.getSubCategories(subCatid)
  .subscribe(subCategories => this.subCat = subCategories);

如果我正确地解释了您的方法,在我看来您正在使用 firebase...如果是这样,在您第一次致电 this.yourService.getSubCategories(subCatid) 后,您的订阅将保持有效,以便您的子类别将是为数据库上的每一次更改更新,即使您更改subCatid,之前的数据库查询也将是活动的。为避免这种情况,我建议您只发射一次snapshotChanges()

getSubCategories(inp_subCatid: string): Observable<any> {
  return this.getSubCategoriesList().snapshotChanges().pipe(
    // finish the subscription after receiving the first value
    take(1),
    map(changes => changes.map(c => 
        ({ key: c.payload.key, ...c.payload.val() })
      ).filter((subCat) => subCat.id === inp_subCatid)
    ));
}

【讨论】:

  • 非常感谢@julianobrasil ...还有一个问题。如果我想过滤特定数据怎么办?喜欢“id”
  • 视情况而定。提供有关您要过滤的位置/内容的更多详细信息。把它放在你的问题中。
  • 好的,我用参数“inp_subCatId”编辑我的评论并订阅方法......希望它有所帮助
  • 好的,我已经更改了答案,并在最后添加了一些重要信息。
  • 嗨@julianobrasil 你能帮我解决一个关于对象stackoverflow.com/questions/61567837/…的额外问题吗@
【解决方案2】:

非常感谢

如果我想过滤特定数据怎么办?喜欢“id”

getSubCategoriesbyId(inp_subCatid): Observable<any>{
  this.getSubCategoriesList().snapshotChanges().pipe(
    map(changes =>
      changes.map(c =>
        ({ key: c.payload.key, ...c.payload.val() })
      )
    )
  ).subscribe(subCategories => {
     subCategories.filter(function (subCat) {
    return subCat.id == inp_subCatid;
  });
  });
}

然后将过滤后的数据取回

this.yourService.getSubCategoriesbyId(subCatid)
  .subscribe(subCategories => console.log(subCategories));

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多