如何在Angular中检测路线变化?

我但愿在AppComponent检测到路线更改。 html

此后,我将检查全局用户令牌以查看他是否已登陆。而后,若是用户未登陆,我能够重定向该用户。 react


#1楼

如下种类的做品可能会为您带来麻烦。 git

// in constructor of your app.ts with router and auth services injected
router.subscribe(path => {
    if (!authService.isAuthorised(path)) //whatever your auth service needs
        router.navigate(['/Login']);
    });

不幸的是,这比我但愿的在路由过程当中的重定向晚。 重定向以前,将调用原始目标组件的onActivate()es6

您能够在目标组件上使用@CanActivate装饰器,但这是a)不集中的,而且b)没法从注入的服务中受益。 github

若是有人能提出一种在提交以前集中受权路线的更好方法,那就太好了。 我相信确定有更好的方法。 bootstrap

这是我当前的代码(如何更改以侦听路线更改?): angular2

import {Component, View, bootstrap, bind, provide} from 'angular2/angular2';
import {ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';    
import {Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';

import { Todo } from './components/todo/todo';
import { About } from './components/about/about';

@Component({
    selector: 'app'
})

@View({
    template: `
        <div class="container">
            <nav>
                <ul>
                    <li><a [router-link]="['/Home']">Todo</a></li>
                    <li><a [router-link]="['/About']">About</a></li>
                </ul>
            </nav>
            <router-outlet></router-outlet>
        </div>
    `,
    directives: [RouterOutlet, RouterLink]
})

@RouteConfig([
    { path: '/', redirectTo: '/home' },
    { path: '/home', component: Todo, as: 'Home' },
    { path: '/about', component: About, as: 'About' }
])

class AppComponent {    
    constructor(location: Location){
        location.go('/');
    }    
}    
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'})]);

#2楼

在Angular 2中,您能够subscribe (Rx事件)路由器实例。 因此你能够作相似的事情 app

class MyClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*whatever*/)
  }
}

编辑 (自rc.1起) ide

class MyClass {
  constructor(private router: Router) {
    router.changes.subscribe((val) => /*whatever*/)
  }
}

编辑2 (2.0.0起) this

另请参阅: Router.events文档

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

#3楼

这里的答案对于router-deprecated是正确的。 对于最新版本的router

this.router.changes.forEach(() => {
    // Do whatever in here
});

要么

this.router.changes.subscribe(() => {
     // Do whatever in here
});

要了解二者之间的区别,请查看此SO问题

编辑

对于最新,您必须执行如下操做:

this.router.events.subscribe(event: Event => {
    // Handle route change
});

#4楼

RxJS 6

router.events.pipe(filter(event => event instanceof NavigationStart))

感谢Peilonrayz(请参阅下面的评论)

新路由器> = RC.3

import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router';

constructor(router:Router) {
  router.events.forEach((event) => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

您还能够按给定事件进行过滤:

import 'rxjs/add/operator/filter';

constructor(router:Router) {
  router.events
    .filter(event => event instanceof NavigationStart)
    .subscribe((event:NavigationStart) => {
      // You only receive NavigationStart events
    });
}

使用pairwise运算符获取上一个和当前事件也是一个好主意。 https://github.com/angular/angular/issues/11268#issuecomment-244601977

import 'rxjs/add/operator/pairwise'; import { Router } from '@angular/router; export class AppComponent { constructor(private router: Router) { this.router.events.pairwise().subscribe((event) => { console.log(event); }); }; }

#5楼

路由器3.0.0-beta.2应该是

this.router.events.subscribe(path => {
  console.log('path = ', path);
});
相关文章
相关标签/搜索