1

I just started with coreUi and Angular 18 and would like to intercept the requests, when the user calls another route. I started with the standard coreUi modern theme and set everything up so far but chaning the route is not beeing intercepted. Maybe someone can help and tell me, what i am doing wrong.

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);
};

_nav.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'
      },
    ]
  },
3
  • Only API calls made through Angular httpClient get intercepted Commented Aug 16, 2024 at 11:16
  • That was so obvious that I overlooked it. But what is the best way to make a changeDetection if the route has changed? I want that the token in the localStorage gets checked for validity on every RouteChange and if its not valid, redirect the user to loginPage Commented Aug 16, 2024 at 11:20
  • updated my answer, you are looking for guards Commented Aug 16, 2024 at 11:31

1 Answer 1

1

If the routing is different, then try running the activate guard on the route change.

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

You are looking for a guard, that checks on each route load.

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

Then we define the guard to check if token present in localStorage else redirect to login.

const authGuard: CanActivateFn = () => {
  return localStorage?.get('token') ? true : this.router.createUrlTree(['/login']);
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer but routing in coreUi is a bit different because i only have a _nav.ts file which includes the routes in another way (edited my question at the bottom). So i need something that detects a route change and than calls the guard.
Thank you naren but working with the navigationEnd or start or so triggers the authGuard many many times. Is there a way to just trigger such a routine one?
@Sithys updated my answer, with the rxjs operators, filter, which filters out extra emissions and debounceTime, which stops multiple emissions of navigation end, when the navigationend is triggered multiple times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.