[英]Angular wait until subscribe is done and give values to other function
我有这个以下 function
文件: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;
});
});
我在以下文件中调用顶部 function
文件:子类别.page.ts
this.SubCategoryService.getSubCategoriesById(subCatid).subscribe((subCategories: any) => {
this.subCat = subCategories ;
})
我得到的问题是我收到以下错误消息:错误类型错误:“this.SubCategoryService.getSubCategorysById(...) is undefined”
我想从文件“subcategory.service.ts”加载数据时获取数据,希望有人能帮助我。
你的方法应该是这样的:
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)
));
}
非常感谢
如果我想过滤特定数据怎么办? 像“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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.