[英]Is there a way to store the retrieved documents from sub-collection Firebase into an array for displaying its info? AngularFirestore
我正在使用 Angular 开发一个网站,目前遇到困难,无法将从 Firebase 子集合中检索到的文档放入数组中。
export class DataService { constructor(private afs: AngularFirestore) { } //retrieving documents from bus stop sub-collection getBusStopsByRoute(id:string){ return this.afs.doc("BusRoute/"+id).collection('busStopList/').snapshotChanges() } }
//function from Ts file for storing retrieved documents in busStops array getBusStops(id:string){ this.dataApi.getBusStopsByRoute(id).subscribe(res=>{ this.busStops=res.map((e:any)=>{ //busStops declared as any const data = e.payload.doc.data(); data.id = e.payload.doc.id; return data; }) console.log('inside subscribe function', this.busStops); }) console.log('Outside subscribe function', this.busStops); }
export class AddBusrouteComponent implements OnInit { form:; FormGroup: title;: string; routeNo:; string: description;: string; destination:; string: arrival;: string: id,: string, buttonName:, string: busStops.. any constructor( private fb; FormBuilder. @Inject(MAT_DIALOG_DATA) data. any; private dataApi. DataService. private dialogRef; MatDialogRef<AddBusrouteComponent> ) { this.id = data.id; this.title = data.title; this.routeNo = data.routeNo; this.description = data.description; this.destination = data.destination; this:arrival = data.arrival. this;buttonName = data.buttonName. // this.busStops = data:busStops. //hard-coded } ngOnInit(), void { this,getBusStops(this:id). this,form = this.fb,group({ id:[this.id, []]. routeNo,[this:routeNo. [Validators,required]]. description, [this:description. [Validators,required]]. destination, [this:destination. [Validators.required]]: arrival, [this.arrival. [Validators.required]], busStops: this.busStops }) console.log('formValue: ', this.form.value) }
Outside subscribe function undefined formValue: {id: 'BusRoute1671550149650', routeNo: 'aasd', description: 'sdasd', destination: 'dasd', arrival: 'asd', …} arrival: "asd" busStops: null description: "sdasd" destination: "dasd" id: "BusRoute1671550149650" routeNo: "aasd" inside subscribe function (3) [{…}, {…}, {…}]
我试图将检索到的文档存储在声明的数组(“busStops”)中,但是 console.log 方法返回了“Undefined”。 根据我的发现,原因是数组只能在 2. 的订阅函数中定义,而不能在函数外定义。
正如您在 2. 中所见,我在订阅函数的内部和外部都使用了 console.log 方法来显示数组 (busStops) 值。 两者的结果是不一样的。 4.结果截图。
是否可以将这些检索到的文档保存在一个数组中?
当您收到bugStops
时,您实际上是在对 Firebase 进行网络调用。 因此,您无法在拨打此电话后立即获得信息。 这就是为什么在外部打印日志时得到Undefined
的原因。
另一方面,如果您subscribe
了网络呼叫。 订阅函数中的所有代码在网络调用完成后被调用。 这就是为什么在外部日志之后打印内部日志的原因。
要保存数据,只需在subscribe
函数范围外定义一个数组,然后将数据放入subscribe
函数内部的数组中即可。
此外,您还可以考虑使用Promise graph
,这样您就可以编写如下代码:
const array = await getBusStops();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.