fra*_*val 6 angular angular-router-guards
我正在CanDeactivate其中一个主要组件中实现功能。为了测试它,我使它始终返回,false因此路线一定不能更改。
在此CanDeactivate实现中,对的调用component.canDeactivate()返回一个解析为false的Promise:
@Injectable()
export class CanDeactivateNewRecord implements
CanDeactivate<NewRecordComponent> {
canDeactivate(
component: NewRecordComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot ):
Observable<boolean>|Promise<boolean>|boolean {
return component.canDeactivate();
}
}
Run Code Online (Sandbox Code Playgroud)
这是带有模块路由定义的片段:
const recordsRoutes: Routes = [
{
path: 'nou',
component: NewRecordComponent,
canDeactivate: [CanDeactivateNewRecord]
},{
path: ':id',
component: RecordComponent
}
];
Run Code Online (Sandbox Code Playgroud)
当我使用from back的服务方法导航到上一页时,有两种不同的情况:Location@angular/common
即使以前的位置是由路由器管理的,调用location.back()足够的次数(与通过应用程序导航的历史记录的长度一样多),也会使导航返回到启动应用程序之前的页面。
这怎么了
我知道这已经太晚了,但我遇到了完全相同的问题,并且认为我会将其留在这里供后代使用。正如另一位人士所说,这是一个尚未解决的已知 Angular 问题。我可以使用一个解决方法,可以在这里找到:github
您的代码的实现将如下所示:
@Injectable()
export class CanDeactivateNewRecord implements CanDeactivate<NewRecordComponent> {
constructor(
private readonly location: Location;
private readonly router: Router;
){}
canDeactivate(component: NewRecordComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot ): Observable<boolean>|Promise<boolean>|boolean {
if(component.canDeactivate()){
return true
}else{
const currentUrlTree = this.router.createUrlTree([], currentRoute);
const currentUrl = currentUrlTree.toString();
this.location.go(currentUrl)
return false
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果 canDeactivate 返回 false,则获取最新的路由并插入回 url 树中。
| 归档时间: |
|
| 查看次数: |
1599 次 |
| 最近记录: |