当我打开页面时调用 Firebase 只发生一次,然后当我导航回它时它永远不会发生

Call to Firebase happens only once when i open the page , then it never happens when i navigate back to it

我正在从我的 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>

您是否在您的应用中使用路由器?如果是这样,您可以订阅一个 Router 实例并在路由更改时执行某些操作。

       constructor(private router: Router) {
        router.events.subscribe(() => shouldGetDresses());
       }

       private shouldGetDresses() {
        this.dressService.getDresses().subscribe(res => {
        this.dress = res;
       });
      }

根据@SeanKPS 的评论,我需要在 ngOnDestroy 上使用 unsubscribe

将我的代码改成这样:

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)]);
  // }
}