在CanLoad Angular 6上指定返回URL

时间:2018-08-29 22:30:01

标签: angular2-routing angular6

我已在路径/projects/1/sub上实现了LazyLoading

然后将CanLoad应用于路线

{ path: 'projects/:projectId/sub', canLoad: [AuthGuard], canActivate: [AuthGuard], loadChildren: './app-sub-line.module#AppSubLineModule' }

导航到节路由模块中的路由/projects/1/sub/1时,登录时的返回URL显示为/projects/:projectId/sub,这实际上是路由路径。

如何在canLoad上构建正确的返回URL?这是AuthService相关代码。

import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { AuthService } from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    }
    else {
      //passing the query string to bring the user back to after signin
      this.router.navigate([''], {
        queryParams: {
          return: state.url
        }
      });

      return false;
    }
  }

  canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    }
    else {
      //passing the query string to bring the user back to after signin
      //alert(route.path)
      this.router.navigate([''], {
        queryParams: {
          return: route.path
        }
      });
      return false;
    }
  }

}

0 个答案:

没有答案