在 Angular 2 / Ionic 2 中通过构造函数刷新数据

Refreshing data through constructor in Angular 2 / Ionic 2

我有 Ionic 2 应用程序,一个视图可显示 3 个不同的数据集。数据在构造函数中加载,并根据页面参数中的变量决定显示哪个数据集。

在 observable 每次成功调用数据时,事件处理程序都会在加载数据时记录成功。但是 这只在我 click/load 第一次查看 时有效。如果我第二次或任何其他时间单击,则不会重新加载数据(无日志)。此外,当我只是控制台记录任何内容时,它不会在第二次+点击时显示。

所以我想知道我应该更改什么每次加载数据以及构造函数如何以这种方式工作。

这就是我的代码的样子。从 namesListProvider 调用 Jsons。

@Component({
  templateUrl: '...',
})
export class ListOfNames {

   ...
    private dataListAll: Array<any> = [];
    private dataListFavourites: Array<any> = [];
    private dataListDisliked: Array<any> = [];


constructor(private nav: NavController, ...) {

    ...
    this.loadJsons();
    console.log('whatever');
  }

   loadJsons(){
    this.namesListProvider.getJsons()
    .subscribe(
      (data:any) => {
        this.dataListFavourites = data[0],
        this.dataListDisliked = data[1],
        this.dataListAll = data[2]

         if (this.actualList === 'mainList') {
            this.listOfNames = this.dataListAll;
            this.swipeLeftList = this.dataListDisliked;
            this.swipeRightList = this.dataListFavourites;
         }
         else if (...) {
            ...
         }
         this.listSearchResults = this.listOfNames;


      }, err => console.log('hey, error when loading names list - ' + err),
      () => console.info('loading Jsons complete')      
    )

  }

我来自 Angular 2 世界,不是 ionic,但是 angular 2 可以选择在 init/destory (ngInit/ngDestory) 上注册回调。 尝试将初始化移至 ngInit,保存订阅处理程序,并且不要忘记在销毁时取消订阅。 我认为你的问题与你没有取消订阅有关.. :\

解决方案是不要在构造函数中执行此操作,而是使用 ngOnInit()。组件只创建一次,因此构造函数只会在第一次创建时被调用。

您的组件 class 必须实现 OnInit 接口:

import { Component, OnInit } from '@angular/core';

@Component({
    templateUrl: '...',
})
export class ListOfNames implements OnInit {
    constructor(...)

    ngOnInit() {
        this.loadJsons();
    }

    private loadJsons() {
        ...
    }
}

您要查找的是来自 Ionic2 页面的 Lifecycle events。因此,您可以使用 Ionic2 公开的一些事件,而不是使用 ngOnInit

Page Event        Description
----------        -----------
ionViewLoaded     Runs when the page has loaded. This event only happens once per page being created and added to the DOM. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewLoaded event is good place to put your setup code for the page.
ionViewWillEnter  Runs when the page is about to enter and become the active page.
ionViewDidEnter   Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page.
ionViewWillLeave  Runs when the page is about to leave and no longer be the active page.
ionViewDidLeave   Runs when the page has finished leaving and is no longer the active page.
ionViewWillUnload Runs when the page is about to be destroyed and have its elements removed. 
ionViewDidUnload  Runs after the page has been destroyed and its elements have been removed.

在您的情况下,您可以像这样使用 ionViewWillEnter 页面事件:

ionViewWillEnter {
  // This will be executed every time the page is shown ...
  this.loadJsons();
  // ...
}

编辑

如果您要异步获取要在该页面上显示的数据,因为您不知道数据准备好需要多长时间,我建议您使用 loading popup 这样用户就可以知道后台发生的事情(而不是在加载数据之前显示几秒钟的空白页面)。您可以像这样轻松地将这种行为添加到您的代码中:

// Import the LoadingController
import { LoadingController, ...} from 'ionic/angular';

@Component({
  templateUrl: '...',
})
export class ListOfNames {

   ...
    private dataListAll: Array<any> = [];
    private dataListFavourites: Array<any> = [];
    private dataListDisliked: Array<any> = [];

    // Create a property to be able to create it and dismiss it from different methods of the class
    private loading: any;


  constructor(private loadingCtrl: LoadingController, private nav: NavController, ...) {

    ...
    this.loadJsons();
    console.log('whatever');
  }

  ionViewWillEnter {
    // This will be executed every time the page is shown ...

    // Create the loading popup
    this.loading = this.loadingCtrl.create({
      content: 'Loading...'
    });

    // Show the popup
    this.loading.present();

    // Get the data
    this.loadJsons();

    // ...
  }

  loadJsons(){
    this.namesListProvider.getJsons()
    .subscribe(
      (data:any) => {
        this.dataListFavourites = data[0],
        this.dataListDisliked = data[1],
        this.dataListAll = data[2]

         if (this.actualList === 'mainList') {
            this.listOfNames = this.dataListAll;
            this.swipeLeftList = this.dataListDisliked;
            this.swipeRightList = this.dataListFavourites;
         }
         else if (...) {
            ...
         }
         this.listSearchResults = this.listOfNames;

      }, err => console.log('hey, error when loading names list - ' + err),
      () => {

        // Dismiss the popup because data is ready
        this.loading.dismiss();

        console.info('loading Jsons complete')}
    )

  }