我正在从ionic 4项目中调用firebase,该项目获取项目列表。只有当我第一次启动该应用程序时,它才会发生,然后,如果我导航到另一个页面,则返回此页面。它显示一个空白列表。这是我的代码:
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)]);
// }
}
这是我在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>
答案 0 :(得分:1)
您是否在应用中使用路由器?如果是这样,您可以订阅路由器实例,并在路由更改时执行一些操作。
-– vs --
答案 1 :(得分:0)
基于@SeanKPS注释,我需要在unsubscribe
上使用ngOnDestroy
。
将我的代码更改为:
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)]);
// }
}