Nirav Parsana
Nirav Parsana

Reputation: 154

Issue while handling back button event in ionic2 application with custom routes

I've implemented back button code in my ionic 2 application as suggested here. but it is not working as expected.

However i'm getting console.log() while back button tapped.

Below is my code for reference.

1) app.routes.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { Login } from '../pages/Login/Login';
import { Orders } from '../pages/Orders/Orders';
import { OrderDetails } from '../pages/Orders/OrderDetails';
import { AssignOrder } from '../pages/Orders/AssignOrder';

const routes: Routes = [
    {
        path: '', redirectTo: '/Orders',
        pathMatch: 'full'
    },
    {
        path: 'Login',
        component: Login
    },
    {
        path: 'Orders',
        component: Orders
    },
    {
        path: 'OrderDetails/:orderid',
        component: OrderDetails
    },
    {
        path: 'AssignOrder',
        component: AssignOrder
    }
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule { }
export const routedComponents = [Login, Orders, OrderDetails, AssignOrder];

2) app.component.ts

import { Component } from '@angular/core';
import { App, Platform, ViewController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@Component({
  templateUrl: 'app.html'
})

export class MyApp {

  constructor(app: App, platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      if (splashScreen) {
        setTimeout(() => {
          splashScreen.hide();
        }, 100);
      }
    });

    platform.registerBackButtonAction(() => {
      let nav = app.getActiveNav();
      console.log(nav);
      let activeView = nav.getActive();
      if (activeView != null) {
        console.log('activeView:' + activeView);
        if (nav.canGoBack()) {
          nav.pop();
        } else if (typeof activeView.instance.backButtonAction === 'function')
          activeView.instance.backButtonAction();
        else nav.parent.select(0); // goes to the first tab
      }
      else {
        console.log('activeView is null');
      }
    });
  }
}

3) Orders.ts

In Orders page, if i click back button it will call function in app.component.ts in which i'm getting "activeView" as undefined in let activeView = nav.getActive(); line. So, i get "activeView is null" is printed in console.(as mentioned in first solution here). Please see this image.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Platform, AlertController, LoadingController } from 'ionic-angular';
import { User } from '../../models/User';
import { Order } from '../../models/Order';
import { UserService } from '../../providers/UserService';
import { OrderService } from '../../providers/OrderService';

@Component({
  selector: 'page-Orders',
  templateUrl: 'Orders.html'
  // providers: [UserService, OrderService],
})
export class Orders implements OnInit {
  orders: Order[];
  selectedOrder: Order;
  user: User;
  error: any;
  showFilter: boolean;
  Search: any;
  loading: any;

  constructor(public router: Router,
    public userService: UserService,
    public orderService: OrderService,
    public platform: Platform,
    public alertCtrl: AlertController,
    public loadingCtrl: LoadingController) {
    this.showFilter = false;
    this.Search = '';
  }

  ngOnInit() {
    if (localStorage.getItem('User') == null) {
      this.router.navigate(['/Login']);
    }
    else {
      this.userService.user = JSON.parse(localStorage.getItem('User'));
      this.getOrders();
    }
  }

  backButtonAction() {

  }
}

4) OrderDetails.ts

In OrderDetails page, if i click back button it will call function in OrderDetails.ts because i'm overriding method of app.component.ts by this.platform.registerBackButtonAction(this.backButtonAction, 10); (as mentioned in second solution here). I'm getting "backButtonAction called" in console log too. but it gives me error at this.gotoOrders(); line. It can't find gotoOrders() function in 'this'. In debug window, i've expand 'this' and i can't see gotoOrders() function there. Please see this image.

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Platform, AlertController, LoadingController } from 'ionic-angular';
import { User } from '../../models/User';
import { Order } from '../../models/Order';
import { UserService } from '../../providers/UserService';
import { OrderService } from '../../providers/OrderService';

@Component({
  selector: 'page-OrderDetails',
  templateUrl: 'OrderDetails.html'
})
export class OrderDetails implements OnInit {
  modal: any;
  @Input() order: Order;
  @Output() close = new EventEmitter();
  user: User;
  loading: any;
  isStaff = this.userService.user.Role == "STAFF";
  navigated = false; // true if navigated here

  constructor(public router: Router,
    private route: ActivatedRoute,
    public userService: UserService,
    public platform: Platform,
    public orderService: OrderService,
    public alertCtrl: AlertController,
    public loadingCtrl: LoadingController) {
    this.platform.registerBackButtonAction(this.backButtonAction, 10);
  }

  ngOnInit() {
    if (this.userService.user == null) {
      this.userService.logout();
    }
    else {
      this.route.params.forEach((params: Params) => {
        if (params['orderid'] !== undefined) {
          let orderid = params['orderid'];
          this.navigated = true;
        }
      });
    }
  }

  backButtonAction() {
    console.log('backButtonAction called');
    this.gotoOrders();
    // if (this.modal && this.modal.index === 0) {
    //   this.modal.dismiss();
    // } else {
    //   /* exits the app, since this is the main/first tab */
    //   this.platform.exitApp();
    //   // this.navCtrl.setRoot(AnotherPage);  <-- if you wanted to go to another page
    // }
  }

  gotoOrders(): void {
    this.router.navigate(['/Orders']);
  }
}

Upvotes: 1

Views: 331

Answers (0)

Related Questions