如何在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);
});
相關文章
相關標籤/搜索