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

Refreshing data through constructor in Angular 2 / Ionic 2

本文关键字:构造函数 刷新 数据 Angular Ionic      更新时间:2023-09-26

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

在可观察对象每次成功调用数据时,事件处理程序都会在加载数据时记录成功。但是这只在我第一次点击/load view 时起作用。如果我点击第二次或任何其他时间,数据不会重新加载(没有日志)。此外,当我只是控制台日志,它不会显示在第二次+点击。

所以我想知道我应该改变来每次加载数据和构造函数是如何以这种方式工作的。

这就是我的代码看起来的样子。json从namesListProvider调用。

@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')      
    )
  }

您要查找的是来自Ionic2页面的生命周期事件。所以不用ngOnInit你可以用Ionic2曝光的一些事件

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

编辑

如果你要异步获取数据,因为你不知道数据准备好需要多长时间,我建议你使用一个加载弹出,这样用户就可以知道后台发生了什么(而不是显示一个空白页面几秒钟,直到数据加载)。您可以像这样轻松地将该行为添加到代码中:

// 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')}
    )
  } 

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

组件类必须实现OnInit接口:

import { Component, OnInit } from '@angular/core';
@Component({
    templateUrl: '...',
})
export class ListOfNames implements OnInit {
    constructor(...)
    ngOnInit() {
        this.loadJsons();
    }
    private loadJsons() {
        ...
    }
}

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