[英]Call to Firebase happens only once when i open the page , then it never happens when i navigate back to it
Am doing a call to the firebase from my ionic 4 project that gets a list of items. 我正在从ionic 4项目中调用firebase,该项目获取项目列表。 it only happens once I launch the app for the first time, then if I navigate to another page then back to this page. 只有当我第一次启动该应用程序时,它才会发生,然后,如果我导航到另一个页面,则返回此页面。 it shows a blank list. 它显示一个空白列表。 here is my code : 这是我的代码:
import { Component, OnInit } from '@angular/core';
import { DressService, Dress } from '../services/dress.service';
@Component({
selector: 'app-list',
templateUrl: 'list.page.html',
styleUrls: ['list.page.scss']
})
export class ListPage implements OnInit {
dress: Dress[];
constructor(private dressService: DressService,
) {
this.dressService.getDresses().subscribe(res => {
this.dress = res;
});
}
ngOnInit() {
}
// add back when alpha.4 is out
// navigate(item) {
// this.router.navigate(['/list', JSON.stringify(item)]);
// }
}
And here is how I view the list in my HTML
page 这就是我在HTML
页面中查看列表的方式
<ion-list>
<ion-item *ngFor="let item of dress" >
<img src="{{item.image_1}}">
<ion-label dir="rtl">
<small>{{item.category}}</small>
<br>
<ion-text color="secondary">
<b>{{item.title}}</b>
</ion-text>
<br>
<ion-badge color="danger">{{item.price}} EGP</ion-badge>
<br>
<small>{{item.city}}</small>
</ion-label>
</ion-item>
</ion-list>
are you using a router in your app? 您在应用中使用路由器吗? If so, you could subscribe to a Router instance and do something when the route changes. 如果是这样,您可以订阅路由器实例,并在路由更改时执行一些操作。
constructor(private router: Router) {
router.events.subscribe(() => shouldGetDresses());
}
private shouldGetDresses() {
this.dressService.getDresses().subscribe(res => {
this.dress = res;
});
}
Based on @SeanKPS Comment, I needed to use unsubscribe
on the ngOnDestroy
. 基于@SeanKPS评论,我需要使用unsubscribe
的ngOnDestroy
。
Changed my code to be like this : 改变我的代码是这样的:
import { Component, OnInit } from '@angular/core';
import { DressService, Dress } from '../services/dress.service';
import { Router } from '@angular/router';
import { Subscription, ObjectUnsubscribedError } from 'rxjs';
@Component({
selector: 'app-list',
templateUrl: 'list.page.html',
styleUrls: ['list.page.scss']
})
export class ListPage implements OnInit {
dress: Dress[];
mySub: any;
constructor(private dressService: DressService,
private router: Router,
) { }
ngOnInit() {
this.mySub = this.dressService.getDresses().subscribe(res => {
this.dress = res;
});
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.mySub.unsubscribe();
}
// add back when alpha.4 is out
// navigate(item) {
// this.router.navigate(['/list', JSON.stringify(item)]);
// }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.