Angular 离子4-检查是否可以返回
我正在寻找一种方法,可以在点击按钮后将用户重定向回所说的返回,或者将用户重定向到特定的路由 我需要在我的代码中添加一个条件,但我似乎找不到方法Angular 离子4-检查是否可以返回,angular,ionic-framework,ionic4,Angular,Ionic Framework,Ionic4,我正在寻找一种方法,可以在点击按钮后将用户重定向回所说的返回,或者将用户重定向到特定的路由 我需要在我的代码中添加一个条件,但我似乎找不到方法 goback() { if("something") { this.navCtlr.setDirection('back'); this.location.back(); } else { this.router.navigate(['/']); } } 在Ionic 3中,我
goback() {
if("something") {
this.navCtlr.setDirection('back');
this.location.back();
}
else {
this.router.navigate(['/']);
}
}
在Ionic 3中,我们使用了canGoBack()1函数……对Ionic 4有什么想法吗?因为它使用角度路由器
谢谢。由于爱奥尼亚4使用角度布线,因此您可以通过角度方式实现此功能,您可以通过创建如下服务来实现:
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(['/']);
}
}
}
我唯一想到的是使用一个有角度的路线守卫来允许或限制返回,即使是解析函数也会有所帮助 并使用导航历史记录服务(RoutingStateService),如中所述 在我使用RoutingStateService处理导航历史记录的情况下,它比直接信任NavigationEnd事件可靠得多(因为RouterStateService在内部使用它) 希望能有帮助。向您致意。您不能将
与deauthref
一起使用吗
<ion-back-button defaultHref="/"></ion-back-button>
但遗憾的是,它不起作用:(我添加了一个console.log(this.currentUrl、this.previousUrl、event.url、event instanceof NavigationEnd);
在函数中侦听事件,并得到一个非常大的/item/item\u id undefined undefined false
答案列表,直到最后一个为真,然后是一组其他答案,其中这个.previousUrl
是(因为它看到了导航结束
)与this.currentUrl
相同。因此,当触发goBack()
时,它会看到一个previousUrl
不应该出现的地方-因此没有达到预期效果。嗨,看起来很有趣(我不确定它是否有效,现在无法检查,很久以前就移动了)-虽然我认为如果没有历史记录,ion back按钮不会显示,但通过添加defaultHref
,如果没有历史记录,它会“创建”它,因此back按钮会在那里:)很好,很简单,但不能阻止或延迟back操作之前的操作(即在返回之前保存数据)