如何动态转到上一页(ionic 4)?

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

目前我正在将我的 ionic 3 项目迁移到 ionic 5,在 ionic 3 中我们使用 this.navCtrl.getPrevious().name; 要通过获取上一页名称来获取上一页名称,我将根据上一页名称导航到不同的页面,你能帮我看看如何在 ionic 4

中获取上一页名称吗

Ionic 4+ 不再使用 navCtrl 并利用 Angular 路由器。

要阅读之前的 URL(路线),您可以通过 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;
    }

};

该服务导入路由器并跟踪更改,以便任何需要先前 URL 信息的组件都可以导入此服务并访问先前的路由:

constructor(
    private previousRouteService: PreviousRouteService
 ) {}

 const prevUrl = this.previousRouteService.getPreviousUrl();