gpt4 book ai didi

angular - Ionic 4 - 检查是否可以返回

转载 作者:行者123 更新时间:2023-12-03 22:07:52 25 4
gpt4 key购买 nike

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

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

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

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

谢谢。

最佳答案

由于 Ionic 4 使用 Angular Routing,因此您可以通过 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;
}
}

现在将该服务注入(inject)到您要检查状况的组件中:

在您的组件中:
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 - Ionic 4 - 检查是否可以返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com