如何通过getLoanById从Firebase获取贷款文档及子集合条目数据
问题原因
loanService.getLoanById() 方法返回的是Promise异步对象,不是直接返回Loan实例,你当前直接将方法返回值赋值给this.loan,拿到的只是Promise对象,不是最终的贷款数据。
解决方法
推荐将数据获取逻辑放到Angular的ngOnInit生命周期钩子中执行(constructor仅用来做依赖注入,不推荐执行业务逻辑),有两种常用写法处理异步返回:
写法1:使用.then处理Promise回调
// 首先导入OnInit接口 import { OnInit } from '@angular/core'; export class DetailPage implements OnInit { loan: Loan; loanId: string; constructor(private route: ActivatedRoute, private loanService: LoanService) { this.loanId = this.route.snapshot.params.id; } ngOnInit() { // 监听Promise完成回调,拿到数据后赋值 this.loanService.getLoanById(this.loanId) .then(res => { this.loan = res; // 可在此处添加拿到数据后的后续业务逻辑 }) .catch(err => { // 错误处理:覆盖贷款不存在、网络请求失败等异常场景 console.error('获取贷款数据失败:', err); }) } }
写法2:使用async/await语法更简洁
import { OnInit } from '@angular/core'; export class DetailPage implements OnInit { loan: Loan; loanId: string; constructor(private route: ActivatedRoute, private loanService: LoanService) { this.loanId = this.route.snapshot.params.id; } async ngOnInit() { try { this.loan = await this.loanService.getLoanById(this.loanId); } catch (err) { console.error('获取贷款数据失败:', err); } } }
提示:页面模板中调用loan的属性时,建议使用
{{loan?.属性名}}可选链写法,或者用<div *ngIf="loan">包裹贷款信息展示区域,避免异步数据还没返回时页面报错。
可选优化:调整loanService的代码可读性
你现有的service代码逻辑是正确的,嵌套Promise可以改成async/await写法更易维护:
async getLoanById(id: string) { // 先获取贷款基础信息 const loanDoc = await firebase.firestore().collection('loans').doc(id).get(); const loan = new Loan(loanDoc.data().username, loanDoc.data().status, loanDoc.data().duedate.toDate(), loanDoc.id); // 再获取贷款条目列表 const itemCollection = await firebase.firestore().collection(`loans/${id}/items`).get(); loan.items = []; itemCollection.forEach(doc => { loan.items.push(new Item(doc.id, doc.data().quantity)); }) return loan; }
内容的提问来源于stack exchange,提问作者kahhao39
相关产品推荐
相关产品推荐

