gpt4 book ai didi

angular - 为什么我需要重新加载我的页面才能从 Angular 中的主题订阅中获取数据?

转载 作者:行者123 更新时间:2023-12-04 08:47:42 25 4
gpt4 key购买 nike

我的 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"是未定义,并且 View 中没有显示任何内容。为了让我的 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(); }

我想知道为什么当我在其他组件中导航并返回到我的组件 statsview 时,我的可观察对象没有从主题订阅中获取数据。

最佳答案

试试BehaviourSubject :

statsSubject = new BehaviourSubject<Stats>(undefined);

它可以容纳一个 currentValue并在订阅时发出它,而常规的 Subject只会在被推到的同一时刻发射。

关于angular - 为什么我需要重新加载我的页面才能从 Angular 中的主题订阅中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64224779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com