Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 routing without component

I want to listen to NavigationStart event and judge if its url attribute is /logout. If so, the router should stop firing successive events, such as RoutesRecognized, GuardsCheckStart, ChildActivationStart, etc., when my listener detects correct NavigationStart event. Otherwise the router should keep on routing.

I don't want to use a component, 'cause I ain't gonna display any /logout view.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';


@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {

  constructor(
    private router: Router,
  ) {
    router.events.filter(event => event instanceof NavigationStart).subscribe(
      (event: NavigationStart) => {
        if (event.url == '/logout') {
          this.logout();
          // TODO stop firing successive events
        }
      }
    );
  }

  ngOnInit() { }

  logout() {
    // TODO logout operations
  }

}
like image 584
KaiserKatze Avatar asked Oct 20 '25 12:10

KaiserKatze


1 Answers

You can use a route guard. When route matches 'logout', the 'YourGuard' will be used to activate or not the route. If the guards returns true, it will be redirected to 'users/sign_in' (just an example). If not, inside the YourGuard you can redirect to other path or do something else.

{ path: 'logout', canActivate: [ YourGuard ], redirectTo: 'users/sign_in' }

You don't need to 'listen' to the route events. Read more about guards here.

like image 186
Christian Benseler Avatar answered Oct 23 '25 00:10

Christian Benseler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!