DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

4 1

Logout with RouteGuard and UrlTree in Angular

We all agreed about not manipulating data inside component or better to say presentation layer.

So I decided to put logout logic inside guard, this way I will be able to just call logout route and done!

For this I've configured my authentication module routes like this:

{
    path: 'login',
    component: AuthComponent,
    data: { registering: false }
  },
  {
    path: 'register',
    component: AuthComponent,
    data: { registering: true }
  },
  {
    path: 'logout',
    component: AuthComponent,
    data: { registering: false },
    canActivate: [LogoutGuard]
  }
Enter fullscreen mode Exit fullscreen mode

I love to keep things as simple and low as possible 😁

For log out I've added canActivate field and passed the LogoutGuard, the guards have the ability to return UrlTree. It is awesome, let's see how the guard implemented:

@Injectable()
export class LogoutGuard implements CanActivate {
  constructor(private store: Store, private router: Router) {
  }

  canActivate(): UrlTree {
    this.store.dispatch(logout());
    return this.router.createUrlTree(['auth', 'login']);
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it!

The canActivate method is dispatching logout action from NgRx solution and then returning the URL tree which is created using Router from angular/router library!

After this, all we need, any where in the APP we can just redirect user to auth/logout and expect it work as expected and user will automatically will be redirected to auth/login route.

Thank you for reading 🙏🏽
Hope you liked ☕

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more