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

为君一笑 提交于 2020-07-22 05:19:05

问题


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


回答1:


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();


来源:https://stackoverflow.com/questions/62847593/how-to-dynamically-go-to-previous-page-ionic-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!