大家好我是角色新手,我想在用户点击刷新按钮或后退按钮时根据某些条件停止路由.如果有人知道帮助我,我不知道这是否可行
constructor(private route: Router) {
this.route.events
.filter(event => event instanceof NavigationEnd)
.pairwise().subscribe((event) => {
if (expression === true){
// stop routing
} else {
// continue routing
}
});
}
Run Code Online (Sandbox Code Playgroud)
是否有可能,如果是的话,我该怎么做?
提前致谢.
A. *_*esa 24
事后我偶然发现了这个问题,但我希望能帮助其他人来这里.
解决方案的主要候选人是路线保护员.
请参阅此处获取解释: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?');
}
}
Run Code Online (Sandbox Code Playgroud)
哪里MyComponent是你的自定义组件,并CanDeactivateGuard会在你登记AppModule的供应商部分,更重要的是,在你的路由配置canDeactivate数组属性:
{
path: 'somePath',
component: MyComponent,
canDeactivate: [CanDeactivateGuard]
},
Run Code Online (Sandbox Code Playgroud)
我发明了另一种解决方案并且有效:
(对于像我这样不想创建警卫来处理这个问题的懒人)
import { NavigationStart, Router } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)
在构造函数中:
constructor(private router: Router) {
router.events.forEach((event) => {
if (event instanceof NavigationStart) {
/* write your own condition here */
if(condition){
this.router.navigate(['/my-current-route']);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
希望您不会懒到更改'/my-current-route'您的路线网址。
| 归档时间: |
|
| 查看次数: |
18303 次 |
| 最近记录: |