了解这些内容的最佳方法是查看 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)。