大家好我是角色新手,我希望在用户根据某些条件点击刷新按钮或后退按钮时停止路由。我不知道这是否可行,如果有人知道帮助我
constructor(private route: Router) {
this.route.events
.filter(event => event instanceof NavigationEnd)
.pairwise().subscribe((event) => {
if (expression === true){
// stop routing
} else {
// continue routing
}
});
}
是否有可能,如果是,我该怎么做?
提前感谢。
答案 0 :(得分:10)
事实上我偶然发现了这个问题,但我希望能帮助其他人来这里。
解决方案的主要候选人是路线保护员。
请看这里的解释: https://angular.io/guide/router#candeactivate-handling-unsaved-changes
相关部分(几乎逐字复制)就是这个实现:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CanDeactivate,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import { MyComponent} from './my-component/my-component.component';
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<MyComponent> {
canDeactivate(
component: MyComponent,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | boolean {
// you can just return true or false synchronously
if (expression === true) {
return true;
}
// or, you can also handle the guard asynchronously, e.g.
// asking the user for confirmation.
return component.dialogService.confirm('Discard changes?');
}
}
MyComponent
是您的自定义组件,而CanDeactivateGuard
将在您的AppModule
的供应商部分注册,更重要的是,在canDeactivate
的路由配置中数组属性:
{
path: 'somePath',
component: MyComponent,
canDeactivate: [
},
答案 1 :(得分:1)
对我来说,简单的方法是在新路线中通过skiplocationchange导航,如下所示:
if(condition === true){
const currentRoute = this.router.routerState;
this.router.navigateByUrl(currentRoute.snapshot.url, { skipLocationChange: true });
// this try to go to currentRoute.url but don't change the location.
}else{
// do nothing;
}
is a no beautiful method but works
答案 2 :(得分:-2)
您可以像下面的代码片段一样使用NavigationStart事件。
this.router.events.subscribe( (event: any) => {
if (event instanceOf NavigationStart) {
/// Your Logic
}
})