每次访问页面时调用一个函数 - Ionic 2

时间:2017-01-16 20:31:03

标签: angular typescript ionic-framework ionic2

我是Ionic 2的新用户并实现了一个小应用程序,我想在每次访问页面时调用REST API函数。遵循我实施的一小段代码。

import { Component } from '@angular/core';
import { NavController, NavParams, ViewController } from 'ionic-angular';
import { ItemService } from '../../providers/item-service';
import { ItemDetailsCartPage } from '../item-details-cart/item-details-cart'

@Component({
  selector: 'page-cart',
  templateUrl: 'cart.html',
  providers: [ItemService]
})
export class CartPage {

  email;
  sessionId;
  public cartData: any;
  public message: any = [];

  constructor(public navCtrl: NavController, 
      public navParams: NavParams, 
      public itemSrvc: ItemService,
      public viewCtrl: ViewController) {}

  ionViewDidLoad() {
    this.email = this.navParams.get('email');
    this.sessionId = this.navParams.get('sessionId');;
    this.loadCart();
  }


  loadCart() {
    this.itemSrvc.getCart(this.email, this.sessionId).then(successData => {
      this.cartData = successData;
      this.message = this.cartData.message;
    },failureData => {
      this.cartData = failureData;
      this.message = [{'itemName':'No items in cart', 'quantity': '', 'imgUrl':''}];
    });
  }

我创建了一个购物车页面,通过调用API显示购物车中添加的商品。我第一次访问购物车页面时,会调用API并收到响应。但是当我第二次再次访问同一页面时,不会调用相同的API函数。

关于这个话题,我可能会有一些重复的问题,但是我没有找到任何相关的答案,经过网上搜索后我发布了这个问题。

4 个答案:

答案 0 :(得分:3)

您应该在ionViewDidEnter()生命周期钩子中添加Api调用,以便每次用户导航到页面时调用它。 请参考以下链接:

nav-controller

答案 1 :(得分:1)

首先阅读“生命周期事件”部分的NavController页面。 我想你也可以用这个方法:

ngOnInit() {
   this.email = this.navParams.get('email');
   this.sessionId = this.navParams.get('sessionId');;
   this.loadCart();
}

还要检查此link

答案 2 :(得分:0)

您是否尝试将this.loadCart()置于构造函数中,并且该工作正常吗?

答案 3 :(得分:0)

import { Component } from '@angular/core';
import { NavController, NavParams, ViewController } from 'ionic-angular';
import { ItemService } from '../../providers/item-service';
import { ItemDetailsCartPage } from '../item-details-cart/item-details-cart'

@Component({
  selector: 'page-cart',
  templateUrl: 'cart.html',
  providers: [ItemService]
})
export class CartPage {

  email;
  sessionId;
  public cartData: any;
  public message: any = [];

  constructor(public navCtrl: NavController, 
      public navParams: NavParams, 
      public itemSrvc: ItemService,
      public viewCtrl: ViewController
      ) {
      this.ionViewDidLoad();  // add your function here
      }

  ionViewDidLoad() {
    this.email = this.navParams.get('email');
    this.sessionId = this.navParams.get('sessionId');;
    this.loadCart();
  }


  loadCart() {
    this.itemSrvc.getCart(this.email, this.sessionId).then(successData => {
      this.cartData = successData;
      this.message = this.cartData.message;
    },failureData => {
      this.cartData = failureData;
      this.message = [{'itemName':'No items in cart', 'quantity': '', 'imgUrl':''}];
    });
  }

LIVE DEMO