1

我正在开发“如果在 Angular 中刷新页面,则阻止路由到辅助视图”代码:https ://www.bennadel.com/blog/3368-prevent-routing-to-secondary-view-if-page-refresh-in- angular-5-0-0.htm

我已经开发了下面的代码,但是代码正在递归,并且相同的 Guard 继续在递归中执行。

@Injectable()
export class DirectAccessGuard implements CanActivate {
    path: ActivatedRouteSnapshot[];
    route: ActivatedRouteSnapshot;
    constructor(private router: Router) { }

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        if (this.router.url === '/' && !this.isPageRefresh()) {
            this.router.navigate(['TOMainLandingPage']);
            return false;
        }
        if (this.isPageRefresh()) {
            this.router.navigateByUrl(this.getUrlWithoutSecondary(state));
            return false;
        }
        return true;
    }

    // I determine if the current route-request is part of a page refresh.
    private isPageRefresh(): boolean {
        return (!this.router.navigated);
    }

    private getUrlWithoutSecondary(routerStateSnapshot: RouterStateSnapshot): UrlTree {
        var urlTree = this.router.parseUrl(routerStateSnapshot.url);
        var segment = urlTree.root;

        while (segment && segment.children) {
            delete (segment.children.secondary);
            segment = segment.children[PRIMARY_OUTLET];
        }
        return (urlTree);
    }
}

注意:如果用户手动键入不存在的路由并在页面上刷新正确的路由,我想停止吗?

4

0 回答 0