我正在寻找在我的AppComponent中检测路由变化。

然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。


当前回答

如果您只是想检查路由/查询参数更改,如localhost:4200/users/1?编辑=1到localhost:4200/users/2?Edit =0你可以像下面这样使用可观察的参数。

import { ActivatedRoute, Params } from '@angular/router';
export class SomeClass implements OnInit {

paramFromRoute;

constructor(private route: ActivatedRoute) { }

ngOnInit() {
  this.paramFromRoute = this.route.snapshot.params['paramName']; // this one is required for getting it first time

  this.route.params.subscribe((params:Params)=>{
    this.paramFromRoute =  params['paramName'] // whenever route is changed, this function will triggered.
  });
  // for queryParams you can subscribe to this.route.queryParams
 }   
}

其他回答

只需在AppRoutingModule上进行更改

@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
  exports: [RouterModule]
})

对于Angular 7,应该这样写:

this.router.events。订阅((事件:事件)=> {})


具体示例如下:

import { Component } from '@angular/core'; 
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';

@Component({
    selector: 'app-root',
    template: `<router-outlet></router-outlet>`
})
export class AppComponent {

    constructor(private router: Router) {

        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
                // Show loading indicator
            }

            if (event instanceof NavigationEnd) {
                // Hide loading indicator
            }

            if (event instanceof NavigationError) {
                // Hide loading indicator

                // Present error to user
                console.log(event.error);
            }
        });

   }
}

我是这么说的:

class ClassName {
  constructor(private router: Router) {
    router.events.subscribe((value) => {
        // see this 
        console.log(value instanceof NavigationEnd) 
    });
  }
}

下面的方法可以帮你解决棘手的问题。

// 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()。

你可以在目标组件上使用@CanActivate装饰器,但这是a)不集中的,b)不能从注入的服务中受益。

如果有人能提出一种更好的方法,在路由提交之前对其进行集中授权,那就太好了。我相信一定有更好的办法。

这是我当前的代码(我如何改变它来监听路由变化?):

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: '/'})]);

RxJS 6

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

感谢Peilonrayz(见下面的评论)

new router >= 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
    });
}

使用成对操作符来获取先前和当前事件也是一个不错的想法。https://github.com/angular/angular/issues/11268#issuecomment-244601977

进口的rxjs /添加/运营商/成对的; import {Router} from '@angular/ Router '; 导出类AppComponent { 构造函数(私有路由器:router) { This.router.events.pairwise ().subscribe((event) => { console.log(事件); }); }; }