Ionic 4 Angular 路由器导航并清除上一页的堆栈/历史记录 [英] Ionic 4 Angular router navigate and clear stack/history of previous page

查看:85
本文介绍了Ionic 4 Angular 路由器导航并清除上一页的堆栈/历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 Angular 路由器的 Ionic 4 开发应用程序.我想导航到另一个页面并清除页面堆栈.在 Android 原生中,它是这样的:

I'm developing an app using Ionic 4 with Angular router. I would like to navigate to another page and clear the page stack. In Android native, it's something like this:

Intent intent = new Intent(NewActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

从我目前所读到的内容来看,可以使用 Ionic NavController 但它在 Ionic 4 中已弃用.我使用 routerLink 了解了按钮,但如果我'我没看错,通过使用该应用程序将立即导航到另一个页面.我需要在导航到另一个页面之前执行一些逻辑.

From what I've read so far, it is possible using Ionic NavController but it is deprecating in Ionic 4. I learnt about buttons with routerLink but if I'm not mistaken, by using that the app will immediately navigate to the other page. I need to execute some logic before navigating to another page .

例如:登录页面.成功登录后,用户应该无法返回登录页面.此外,通过单击登录"按钮,它应该调用一个函数来处理登录并决定导航/不导航到另一个页面.

For example: Login page. After successful login, the user shouldn't be able to go back to the login page. Also, by clicking the 'login' button, it should call a function to process the login and decide to navigate/not navigate to another page.

有什么方法可以通过 Angular 路由器实现这一点,还是需要依赖已弃用的 Ionic NavController?

Is there any way that I can achieve this with Angular router or do I need to rely on the deprecating Ionic NavController?

推荐答案

例如一个登录页面,它是一个根页面 ('/login'),点击登录按钮后导航到像这样的新页面:

For example of a login page, which is a root page ('/login'), after clicking the login button navigate to a new page like this:

onLogin() {
   this.router.navigateByUrl('/profile', { replaceUrl: true }) 
}

它将页面历史条目替换为一个新的 URL,在这种特殊情况下使用 '/profile'.使用普通的 或浏览器的后退按钮后,您将不会被重定向到登录页面,而是被重定向到前一页.假设您的页面导航是这样的:主页 -> 登录 -> 个人资料,但历史记录只会记住 主页 -> 个人资料,因此点击 处的后退按钮>个人资料页面将带您回到首页.

It replaces the page history entry with a new URL, in this particular case with '/profile'. After using a plain <ion-back-button></ion-back-button> or the browser's back button, you will not be redirected to the login page but to the preceding page. Let's say your page navigation is like this: home -> login -> profile, but the history will remember only home -> profile, thus hitting the back button at profile page will take you back to home.

对于完整的解决方案,您可以将其与 Angular Route Guards 结合使用,以防止基于某些条件(例如用户已登录)访问页面.可以在这个答案中找到如何操作的提示.

For a complete solution, you can combine this with Angular Route Guards, to prevent accessing pages based on some conditions (e.g. user is logged in). Hints how to do it can be found in this answer.

这篇关于Ionic 4 Angular 路由器导航并清除上一页的堆栈/历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆