【发布时间】:2021-01-06 15:26:05
【问题描述】:
我有一些数据存储在 Firebase 实时数据库中。 我希望我的 Angular 应用程序在启动时加载并显示它。我有一个加载数据的 TripService 和一个主 AppComponent。在 TripService 中,我使用 subscribe() 方法检索数据。但是,我无法将此数据发送到 AppComponent。我尝试将此订阅转换为 Promise,但我的解决方案不起作用。你能告诉我我犯了什么错误吗?另外,如何确保 AppComponent 在 TripService 加载后读取数据?
这是trip.service.ts中最重要的代码
export class TripService {
trips: any;
private db: AngularFireDatabase
constructor(database: AngularFireDatabase) {
this.db = database;
}
async loadAllTrips(){
this.db.list('trips').snapshotChanges()
.pipe(map(changes =>
changes.map(c =>
({key: c.key, ...<Object>c.payload.val()}))))
.subscribe(data => {
this.trips = data;})
}
}
这是app.component.ts中最重要的代码
export class AppComponent implements OnInit {
ngOnInit() {
this.tripService.loadAllTrips()
.then(() => {this.trips = this.tripService.trips;);
}
trips: any;
}
【问题讨论】:
-
不不,我需要另一个组件中的数据
-
这与组件无关。这就是 rxjs 的工作原理……
标签: javascript angular typescript firebase es6-promise