Search code examples
ionic4

How to dynamically go to previous page (ionic 4)?


Currently im migrating my ionic 3 project to ionic 5, in ionic 3 we use this.navCtrl.getPrevious().name; to get the previous page name by getting the previous page name i will navigate to different pages based on the previous page name can you please help me how can i get previous page name in ionic 4


Solution

  • Ionic 4+ moved away from navCtrl and leverages Angular Router.

    To read previous URL (route) you may do it via PreviousRouteService:

    import { Injectable } from '@angular/core';
    import { Router, RoutesRecognized } from '@angular/router';
    import { filter, pairwise } from 'rxjs/operators';
    
    @Injectable({
        providedIn: "root"
    })
    export class PreviousRouteService {
    
        private previousUrl: string;
        private currentUrl: string;
    
        constructor(private router: Router) {
    
            this.currentUrl = this.router.url;
            this.previousUrl = null;
    
            this.router.events
                        .pipe(filter((event: any) => event instanceof RoutesRecognized), pairwise())
                        .subscribe((events: RoutesRecognized[]) => {
                            this.previousUrl = events[0].urlAfterRedirects;
                            this.currentUrl = events[1].urlAfterRedirects;
                        });
    
        }
    
        public getPreviousUrl() {
            return this.previousUrl;
        }
    
    };
    

    The service imports Router and tracks changes so that any component that needs previous URL information can import this service and access previous route:

    constructor(
        private previousRouteService: PreviousRouteService
     ) {}
    
     const prevUrl = this.previousRouteService.getPreviousUrl();