首页 > 解决方案 > 如何在 ionic 4 中从一页移动到另一页?

问题描述

我想从一页移动到另一页,为此我在home.page.html文件中写了下面的代码。

<div style="display: flex; justify-content: center; margin-top: 20px; margin-bottom: 20px;">
    <ion-button (click)="goToLoginPage()" size="large">Continue</ion-button>
</div>

下面是home.page.ts文件代码。

export class HomePage {

  constructor(public navController: NavController) {

  }

  goToLoginPage(){
    this.navController.navigateForward(LoginVCPage) // Getting error at this line.
  }
}

下面是错误截图。

在此处输入图像描述

任何帮助将不胜感激

标签: ionic-frameworkionic4

解决方案


在 Ionic 4 中NavController,不推荐使用。请参阅迁移指南中的此声明:

在 V4 中,导航收到了最多的变化。现在,我们不再使用 Ionic 自己的 NavController,而是与官方 Angular Router 集成。

Angular 在一个单独的文件中管理它的路由,在 Ionic 4 中这个文件被命名为app-routing.module.ts. 每次使用 CLI 创建新页面时,都会在数组中ionic g page pagename自动创建一个新条目。routesapp-routing.module.ts

因此,假设您已经创建了一个测试页面,并且现在有以下路线app-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'test', loadChildren: './test/test.module#TestPageModule' },
];

您可以通过向您的按钮添加一个 href 属性以及'/test'要移动到的页面的相应路径(例如 )来移动到另一个页面:

<ion-button href="/test">Move to test page</ion-button>

您还可以使用此处routerLink指出的指令:

<ion-button [routerLink]="['/test']">Move to test page</ion-button>

如果您想/需要以编程方式导航,则必须将路由器服务注入您的页面/组件并navigateByUrl像这样调用:

constructor(private router: Router) { }

goToTestPage() {
    this.router.navigateByUrl('/test');
}

另请参阅有关路由的 Angular 文档和有关此主题的Ionic v4 文档。


推荐阅读