【发布时间】:2020-10-06 22:52:19
【问题描述】:
我在我的 Angular 应用程序中遇到了问题。
我想使用 ngOnInit() 和订阅主题从我的组件“statsview”中的 firebase 获取数据。
这是对主题的订阅。
export class StatsviewComponent implements OnInit, OnDestroy {
stats : Stats;
statsSubscription : Subscription;
constructor(private hbService:HbService) { }
ngOnInit(): void {
this.statsSubscription = this.hbService.statsSubject.subscribe(
(stats:Stats) => {
this.stats= stats;
}
);
this.hbService.statsSubject.next(this.stats);
}
这是我要显示的内容。
<h1>nc : {{ stats.nc }}</h1>
<h1>Réponse au 1er Message : {{ stats.firstMess }}</h1>
<h1>Date : {{ stats.firstDate }}</h1>
<h1>FC : {{ stats.fc }} </h1>
当应用程序加载页面时,来自 observable 的值“stats”会获得正确的数据,并且当我继续使用其他组件并返回我的“statsview”值时它可以工作但“ stats" 是undefined,视图中不会出现任何内容。要让我的 statsview 正常工作,我需要重新加载页面 (F5)...
我不明白为什么当我在我的应用程序中导航并返回我的 statview 而不刷新页面时它不能正常工作。
我的主题声明在 hbService 中,我将函数 getStats() 放在构造函数中。
这是hbService中的getStats()函数。
getStats(){
firebase.database().ref('/stats/').on('value', (data: DataSnapshot) => {
this.stats = data.val() ? data.val() : this.stats;
this.statsSubject.next(this.stats);
});
这里是hbService的构造函数中调用的函数和主题的声明。
export class HbService {
stats : Stats;
statsSubject = new Subject<Stats>();
constructor(private router: Router) { this.getHbs(); this.getStats(); }
我想知道为什么当我在其他组件中导航并返回到我的组件统计视图时,我的 observable 没有从主题订阅中获取数据。
【问题讨论】:
-
你为什么在组件
ngOnInit中调用next?很确定那一刻是未定义的 -
非常感谢它现在可以工作了!我从 hbService 调用了 next() 函数,此时 stats 不是未定义的。所以,以确保我理解。当我从 hbService 调用 next 时它起作用了,因为 promise 有时间将数据恢复到统计数据中吗?
-
我不能完全确定问题的原因。我刚刚看到您从组件和服务中都调用了
next。通常服务会先推送数据,因为服务是在应用程序启动期间实例化的,在组件之前。看起来该组件正在覆盖它,因为它立即调用了next。subscribe中的代码将始终在this.hbService.statsSubject.next(this.stats);之后调用,因为它是异步的。 -
是的,所以它起作用了,因为在
this.stats之前是来自susbribe的变量,所以在调用next(因为异步)并使用hbServiceemitStats(){ this.statsSubject.next(this.stats); }中编写的函数时它是空的更好,因为this.stats来自hbService所以它不是空的。
标签: angular rxjs observable