当我直接点击 URL 时,Angular Guard 服务无法工作

发布于 2025-01-12 09:33:28 字数 5861 浏览 1 评论 0原文

我已经在我的应用程序中实现了路由和防护服务。通过单击锚标记按钮进行导航时,它工作正常。但是,当我尝试通过点击 url 进行导航时,它返回空页面。

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PageForbiddenComponent } from './error/page-forbidden/page-forbidden.component';
import { PageNotfoundComponent } from './error/page-notfound/page-notfound.component';
import { HomeComponent } from './home/home.component';
import { LayoutComponent } from './layout/layout.component';
import { LoginComponent } from './login/login.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService } from './service/auth-guard.service';
import { TaskComponent } from './task/task.component';

const routes: Routes = [
  { path: '', component: LoginComponent },
  {
    path: 'layout',
    component: LayoutComponent,
    canActivateChild: [AuthGuardService],
    children: [
      { path: '', component: HomeComponent },
      {
        path: 'profile',
        component: ProfileComponent,
      },
      {
        path: 'task',
        component: TaskComponent,
      },
    ],
  },
  { path: '403', component: PageForbiddenComponent },
  { path: '404', component: PageNotfoundComponent },
  { path: '**', redirectTo: '404' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

auth-guard.service.ts

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  CanActivateChild,
  Route,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { IChildMenuEntity } from '../model/login/IChildMenuEntity';
import { IUserDetailsEntity } from '../model/login/IUserDetailsEntity';
import { AppSettingsService } from './app-settings.service';
import { LoginService } from './login.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuardService implements CanActivate, CanActivateChild {
  userDetails!: IUserDetailsEntity;
  childMenuItems!: IChildMenuEntity[];
  token: string;
  defaultPage = '/layout';

  constructor(
    private _router: Router,
    private _loginService: LoginService,
    private _appSettings: AppSettingsService
  ) {}
  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    this.token = localStorage.getItem(
      this._appSettings.appConstants.tokenHeader
    );
    this.userDetails = this._loginService.userDetails;
    if (this.token) {
      if (this.userDetails == null || this.userDetails == undefined) {
        this._loginService.GetCurrentUserDetails().subscribe((data) => {
          this._loginService.userDetails = data;
          this.userDetails = this._loginService.userDetails;
          return this.AuthorizeRoute(state, this.userDetails);
        });
      } else {
        return this.AuthorizeRoute(state, this.userDetails);
      }
    } else {
      this._router.navigateByUrl('/');
      return false;
    }
  }
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    this.token = localStorage.getItem(
      this._appSettings.appConstants.tokenHeader
    );
    this.userDetails = this._loginService.userDetails;
    if (this.token) {
      if (this.userDetails == null || this.userDetails == undefined) {
        this._loginService.GetCurrentUserDetails().subscribe((data) => {
          this._loginService.userDetails = data;
          this.userDetails = this._loginService.userDetails;
          // return this.AuthorizeRoute(state, this.userDetails);
          this._router.navigateByUrl(this.defaultPage);
        });
      } else {
        // return this.AuthorizeRoute(state, this.userDetails);
        this._router.navigateByUrl(this.defaultPage);
      }
    } else {
      this._router.navigateByUrl('/');
      return false;
    }
  }

  GetConfiguredRoutes = (): Route[] => {
    return this._router.config[1].children;
  };

  AuthorizeRoute = (
    state: RouterStateSnapshot,
    userDetails: IUserDetailsEntity
  ): any => {
    console.log(state.url);

    if (userDetails != null) {
      let configuredRoutes = this.GetConfiguredRoutes();
      let sideMenus = [];
      userDetails.sideMenu.forEach((x) => {
        x.childMenuEntities.forEach((y) => {
          sideMenus.push(y.routeURL);
        });
      });

      console.log(sideMenus);

      if (this.defaultPage.toLowerCase() === state.url.toLowerCase()) {
        if (configuredRoutes.find((x) => x.path == '')) {
          return true;
        } else {
          this._router.navigateByUrl('/404');
          return false;
        }
      } else {
        console.log('other than home');

        if (
          configuredRoutes.find(
            (x) => `${this.defaultPage}/${x.path.toLowerCase()}` == state.url
          )
        ) {
          console.log('Route Configured');

          if (sideMenus.find((x) => x.toLowerCase() === state.url)) {
            console.log('valid route');
            return true;
          } else {
            this._router.navigateByUrl('/403');
            return false;
          }
        } else {
          this._router.navigateByUrl('/404');
          return false;
        }
      }
    }
  };
}

这是我在防护和路由中所做的配置。因此,当我尝试使用侧面菜单导航时,它工作正常。但是,当我在浏览器搜索中输入 url 时,它没有按预期工作,即它导航到 URL:localhost:4200/ 而不是导航到例如 URL:localhost:4200/layout/profile。

请帮我!!!! 提前致谢!!!

I have implemented Routing and Guard Service in my application. When navigate by clicking by anchor tag button it is working fine. But, when I try to navigate by hitting url it is returning empty page.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PageForbiddenComponent } from './error/page-forbidden/page-forbidden.component';
import { PageNotfoundComponent } from './error/page-notfound/page-notfound.component';
import { HomeComponent } from './home/home.component';
import { LayoutComponent } from './layout/layout.component';
import { LoginComponent } from './login/login.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService } from './service/auth-guard.service';
import { TaskComponent } from './task/task.component';

const routes: Routes = [
  { path: '', component: LoginComponent },
  {
    path: 'layout',
    component: LayoutComponent,
    canActivateChild: [AuthGuardService],
    children: [
      { path: '', component: HomeComponent },
      {
        path: 'profile',
        component: ProfileComponent,
      },
      {
        path: 'task',
        component: TaskComponent,
      },
    ],
  },
  { path: '403', component: PageForbiddenComponent },
  { path: '404', component: PageNotfoundComponent },
  { path: '**', redirectTo: '404' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

auth-guard.service.ts

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  CanActivateChild,
  Route,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { IChildMenuEntity } from '../model/login/IChildMenuEntity';
import { IUserDetailsEntity } from '../model/login/IUserDetailsEntity';
import { AppSettingsService } from './app-settings.service';
import { LoginService } from './login.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuardService implements CanActivate, CanActivateChild {
  userDetails!: IUserDetailsEntity;
  childMenuItems!: IChildMenuEntity[];
  token: string;
  defaultPage = '/layout';

  constructor(
    private _router: Router,
    private _loginService: LoginService,
    private _appSettings: AppSettingsService
  ) {}
  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    this.token = localStorage.getItem(
      this._appSettings.appConstants.tokenHeader
    );
    this.userDetails = this._loginService.userDetails;
    if (this.token) {
      if (this.userDetails == null || this.userDetails == undefined) {
        this._loginService.GetCurrentUserDetails().subscribe((data) => {
          this._loginService.userDetails = data;
          this.userDetails = this._loginService.userDetails;
          return this.AuthorizeRoute(state, this.userDetails);
        });
      } else {
        return this.AuthorizeRoute(state, this.userDetails);
      }
    } else {
      this._router.navigateByUrl('/');
      return false;
    }
  }
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    this.token = localStorage.getItem(
      this._appSettings.appConstants.tokenHeader
    );
    this.userDetails = this._loginService.userDetails;
    if (this.token) {
      if (this.userDetails == null || this.userDetails == undefined) {
        this._loginService.GetCurrentUserDetails().subscribe((data) => {
          this._loginService.userDetails = data;
          this.userDetails = this._loginService.userDetails;
          // return this.AuthorizeRoute(state, this.userDetails);
          this._router.navigateByUrl(this.defaultPage);
        });
      } else {
        // return this.AuthorizeRoute(state, this.userDetails);
        this._router.navigateByUrl(this.defaultPage);
      }
    } else {
      this._router.navigateByUrl('/');
      return false;
    }
  }

  GetConfiguredRoutes = (): Route[] => {
    return this._router.config[1].children;
  };

  AuthorizeRoute = (
    state: RouterStateSnapshot,
    userDetails: IUserDetailsEntity
  ): any => {
    console.log(state.url);

    if (userDetails != null) {
      let configuredRoutes = this.GetConfiguredRoutes();
      let sideMenus = [];
      userDetails.sideMenu.forEach((x) => {
        x.childMenuEntities.forEach((y) => {
          sideMenus.push(y.routeURL);
        });
      });

      console.log(sideMenus);

      if (this.defaultPage.toLowerCase() === state.url.toLowerCase()) {
        if (configuredRoutes.find((x) => x.path == '')) {
          return true;
        } else {
          this._router.navigateByUrl('/404');
          return false;
        }
      } else {
        console.log('other than home');

        if (
          configuredRoutes.find(
            (x) => `${this.defaultPage}/${x.path.toLowerCase()}` == state.url
          )
        ) {
          console.log('Route Configured');

          if (sideMenus.find((x) => x.toLowerCase() === state.url)) {
            console.log('valid route');
            return true;
          } else {
            this._router.navigateByUrl('/403');
            return false;
          }
        } else {
          this._router.navigateByUrl('/404');
          return false;
        }
      }
    }
  };
}

This are the configuration i have done in the guard and routing. So when i try to navigate using side menu it is working fine. But when i enter url in the browser search it is not working as expected i.e it is navigating to the URL:localhost:4200/ not to the eg-URL:localhost:4200/layout/profile.

Please help me!!!!
Thanks in advance!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文