【问题标题】:How to trigger back button from Ionic5 code如何从 Ionic5 代码触发后退按钮
【发布时间】:2023-07-05 07:02:02
【问题描述】:

我需要触发相同的功能,导航菜单中的后退按钮将从代码中触发。

    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>

我正在使用

    this.router.navigate(['/previousPage', {
        demoMode: false
    }]);

但是在开始视图中与 D3 存在奇怪的不一致,在后退按钮上不会出现这种不一致,但在 router 上会出现这种不一致。我只是不知道后退按钮在后台触发了哪个功能。猜猜它一定类似于navCtrl.pop

【问题讨论】:

  • 你试过了吗? forum.ionicframework.com/t/…
  • 我想我在某种程度上做到了,我有navCtrl,这导致了其他问题,所以我只使用了router。不过我可能会再试一次,因为我现在遇到的问题比其他问题更严重。

标签: javascript ionic-framework angular-ui-router ionic5


【解决方案1】:

了解这些内容的最佳方法是查看 Ionic 的源代码。 Ionic 的源代码组织得非常好,所以大多数时候很容易找到某些组件在幕后的作用。

关于您的问题,this is the code of the ion-back-button directive

基于此,Ionic 似乎使用 IonRouterOutlet(如果可用)或 NavController 否则:

if (this.routerOutlet && this.routerOutlet.canGoBack()) {
  this.navCtrl.setDirection('back', undefined, undefined, this.routerAnimation);
  this.routerOutlet.pop();
  // ...
} else if (defaultHref != null) {
  this.navCtrl.navigateBack(defaultHref, { animation: this.routerAnimation });      
}

知道了这一点,你就可以编写一个做同样事情的方法。请查看this Stackblitz demo

代码中最相关的部分是DetailsPage

import { Component, Optional } from "@angular/core";
import { IonRouterOutlet, NavController } from "@ionic/angular";

@Component({
  selector: "app-details",
  templateUrl: "./details.page.html",
  styleUrls: ["./details.page.scss"]
})
export class DetailsPage {
  constructor(
    @Optional() private routerOutlet: IonRouterOutlet,
    private navCtrl: NavController
  ) {}

  public goBack(): void {
    if (this.routerOutlet && this.routerOutlet.canGoBack()) {
      this.navCtrl.setDirection("back");
      this.routerOutlet.pop();
    } else {
      this.navCtrl.navigateBack("/home");
    }
  }
}

在演示中,我省略了设置自定义页面过渡,但如果您在应用中使用自定义页面过渡,则可以这样做。

顺便说一句,如果您想简化该代码,我想您可以直接使用 this.navCtrl.navigateBack("/home");,因为 Ionic 5 中的 NavController 在幕后使用 Angular 的路由器(可以看出 here)。

【讨论】:

    最近更新 更多