Ionic 4 - 检查是否可以返回

Ionic 4 - check if can go back

我正在寻找一种方法,如果存在返回,则在单击按钮后将用户重定向回来,否则重定向到特定路线。

我需要在我的代码中添加一个条件,但我似乎没有找到方法。

  goback() {
    if("something") {
      this.navCtlr.setDirection('back');
      this.location.back();
    }
    else {
      this.router.navigate(['/']);
    }
  }

在 Ionic 3 中,我们有 canGoBack() 1 个函数……对 Ionic 4 有什么想法吗?因为它使用 Angular 路由器...

谢谢。

由于 Ionic 4 使用 Angular 路由,因此您可以通过 Angular 方式实现此功能,您可以通过创建这样的服务来实现它:

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable()
export class PreviousRouteService {

  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl() {
    return this.previousUrl;
  }    
}

现在将该服务注入到您要检查条件的组件中:

在你的组件中:

import { Component } from '@angular/core';
import { PreviousRouteService } from '../services/previous-route.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(private previousRouteService: PreviousRouteService) {}  

  goback() {
    if(this.previousRouteService.getPreviousUrl()) {
      this.navCtlr.setDirection('back');
      this.location.back();
    }
    else {
      this.router.navigate(['/']);
    }
  }
}

我想到的唯一想法是使用 Angular 路由保护来允许或限制返回,即使是 resolve 函数也会有所帮助。

那并使用导航历史服务 (RoutingStateService),例如 https://blog.hackages.io/our-solution-to-get-a-previous-route-with-angular-5-601c16621cf0 中提到的 在我使用 RoutingStateService 处理我的导航历史记录的情况下,它比直接信任 NavigationEnd 事件可靠得多(因为 RouterStateService 在内部使用它)。

希望对您有所帮助。最好的问候。

你不能用 <ion-back-button>defautHref 吗?

<ion-back-button defaultHref="/"></ion-back-button>