我已经多次尝试创建一个Angular 7服务,该服务将从Firestore返回一个observable,但最新版本不返回任何数据(迄今为止最好的结果);我使用了Angularfire2,因为它应该是为可观察的设计而且更容易使用。
我的服务是data4eatery.ts:
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { IeTables } from './../components/models/eateries-model';
@Injectable({
providedIn: 'root'
})
export class Data4eateryService {
tablesCollection: AngularFirestoreCollection<IeTables>;
tables: Observable<IeTables[]>;
constructor(private afs: AngularFirestore) { }
getTables() {
this.tablesCollection = this.afs.
collection('eEatery').doc('J3XTNqSWGzmU4261BDHD'). //hard coded for testing
collection('eTable');
this.tables = this.tablesCollection.valueChanges();
return this.tables;
}
}
来自调用组件的代码:
tables: IeTables[] = [];
constructor( private data4eateryservice: Data4eateryService) { }
ngOnInit() {
const tablesObservable = this.data4eateryservice.getTables();
tablesObservable.subscribe((tablesData: IeTables[]) => {
this.tables = tablesData;
});
console.log('Tables', this.tables);
}
这会返回Tables []
我找到的所有教程都从同一组件中的常量返回observable。我一直试图打开和关闭这几周,所以请帮助我。
observable执行异步操作。所以你需要在调用subscribe
回调后分配值,如下所示:
tables: IeTables[] = [];
constructor( private data4eateryservice: Data4eateryService) { }
ngOnInit() {
const tablesObservable = this.data4eateryservice.getTables();
console.log('1 - OnInit Called');
tablesObservable.subscribe((tablesData: IeTables[]) => {
this.tables = tablesData;
console.log('2 - this.tables is set');
});
console.log('3 - After subscription');
}
以上代码输出到控制台:
1 - OnInit Called
3 - 订阅后
2 - this.tables已设置
因此,在订阅返回值之前,不会设置this.tables
。所以你需要将console.log
移动到subscribe
回调内部,如下所示:
ngOnInit() {
const tablesObservable = this.data4eateryservice.getTables();
tablesObservable.subscribe((tablesData: IeTables[]) => {
this.tables = tablesData;
console.log('this.tables: ',this.tables);
});
}
我想你需要更加熟悉来自Observable
的RxJS
的基本原理
官方Angular Docs:https://angular.io/guide/observables
教程:https://appdividend.com/2018/12/08/angular-7-observables-tutorial-with-example/
另一个教程:https://codecraft.tv/courses/angular/http/http-with-observables/