代码之家  ›  专栏  ›  技术社区  ›  Sithys

CoreUI与Angular 18-拦截器不拦截http请求

  •  1
  • Sithys  · 技术社区  · 5 月前

    我刚开始使用coreUi和Angular 18,希望在用户调用另一条路由时拦截请求。我从标准的coreUi现代主题开始,到目前为止已经设置好了一切,但改变路线并没有被拦截。也许有人可以帮助我,告诉我我做错了什么。

    app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
    import { Title } from '@angular/platform-browser';
    
    import { IconSetService } from '@coreui/icons-angular';
    import { iconSubset } from './icons/icon-subset';
    
    @Component({
      selector: 'app-root',
      template: '<router-outlet />',
      standalone: true,
      imports: [RouterOutlet]
    })
    export class AppComponent implements OnInit {
      title = 'CoreUI Pro Angular Admin Template';
    
      constructor(
        private router: Router,
        private titleService: Title,
        private iconSetService: IconSetService
      ) {
        this.titleService.setTitle(this.title);
        // iconSet singleton
        this.iconSetService.icons = { ...iconSubset };
      }
    
      ngOnInit(): void {
        this.router.events.subscribe((evt) => {
          if (!(evt instanceof NavigationEnd)) {
            return;
          }
        });
      }
    }
    

    app.config.ts

    import { ApplicationConfig, importProvidersFrom } from '@angular/core';
    import { provideAnimations } from '@angular/platform-browser/animations';
    import {
      provideRouter,
      withEnabledBlockingInitialNavigation,
      withHashLocation,
      withInMemoryScrolling,
      withRouterConfig,
      withViewTransitions
    } from '@angular/router';
    
    import { DropdownModule, SidebarModule } from '@coreui/angular-pro';
    import { IconSetService } from '@coreui/icons-angular';
    import { routes } from './app.routes';
    import { provideHttpClient, withInterceptors } from '@angular/common/http';
    import { authInterceptor } from '../interceptors/auth.interceptor';
    import { JwtModule } from '@auth0/angular-jwt';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideRouter(routes,
          withRouterConfig({
            onSameUrlNavigation: 'reload'
          }),
          withInMemoryScrolling({
            scrollPositionRestoration: 'top',
            anchorScrolling: 'enabled'
          }),
          withEnabledBlockingInitialNavigation(),
          withViewTransitions(),
          withHashLocation()
        ),
        importProvidersFrom(SidebarModule, DropdownModule, JwtModule.forRoot({})),
        IconSetService,
        provideAnimations(),
        provideHttpClient(withInterceptors([authInterceptor])), 
      ]
    };
    

    auth.interceptor.ts

    import { HttpInterceptorFn } from '@angular/common/http';
    
    export const authInterceptor: HttpInterceptorFn = (req, next) => {
        console.log("Intercepting Requests")
        return next(authReq);
    };
    

    _导航ts

      {
        name: 'Pages',
        url: '/login',
        iconComponent: { name: 'cil-star' },
        children: [
          {
            name: 'Login',
            url: '/login',
            icon: 'nav-icon-bullet'
          },
          {
            name: 'Register',
            url: '/register',
            icon: 'nav-icon-bullet'
          },
        ]
      },
    
    1 回复  |  直到 5 月前
        1
  •  1
  •   Naren Murali    5 月前

    如果路线不同,请尝试在路线更改时运行激活防护。

     ngOnInit(): void {
        this.router.events.pipe(
            filter((e): e is NavigationEnd => e instanceof NavigationEnd),
            debounceTime(100),
        ).subscribe((evt) => {
            authGuard();
        });
      }
    

    您正在寻找一名警卫,负责检查每条路线的货物。

    [
      { path: 'gallery', component: GalleryComponent, canActivate: [authGuard] },
      { path: 'hello', component: HelloComponent, canActivate: [authGuard] }
    ]
    

    然后我们定义一个守卫来检查localStorage中存在的令牌是否重定向到登录。

    const authGuard: CanActivateFn = () => {
      return localStorage?.get('token') ? true : this.router.createUrlTree(['/login']);
    };
    
    推荐文章