Angular 2路由器事件不是第一次触发?

问题描述:

我从一个组件路由到另一个组件。一旦路线完成,我想使用以前的路线URL。我已经将下面的代码放到了要传递到的组件的构造函数中,但是它不会在第一条路径上触发。在第一条路线之后,该功能每次都会触发。Angular 2路由器事件不是第一次触发?

this.router.events 
     .filter(e => e instanceof NavigationEnd) 
     .pairwise().subscribe((e) => { 
      console.log(e); 
    }); 

如果我删除它似乎开枪第一路线成对的功能,但它仅列出当前的路由,而不是以前的路线。

router.events 
    .filter(e => e instanceof NavigationEnd) 
    .subscribe(e => { 
    console.log(e); 
}); 

我的目标是在新组件路由到时检索先前的路由。我在这里做错了什么?

+0

这确实需要一个服务或至少一个在你的根组件中的处理程序。 – lexith

我只是偶然发现了同样的问题,并找到了它的原因:订阅路由器事件的服务从来没有像依赖注入器那样实例化,因为服务没有在该路由注入。

一个服务似乎只在被注入某个地方时才会立即执行。

因此,如果整个代码(不是事件)被调用,那么检查你的第一个路由。

我有完全相同的情况,我发现it's too late订阅子元件的构造函数中的NavigationEnd和Pairwise。

你可以通过像下图所示的服务订阅路由器在你的根组件和共享路线数据:

events.service.ts

import { Injectable } from '@angular/core'; 
import { RouteChanged } from '../models/route-changed.model'; 
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 

@Injectable() 
export class EventsService { 
    public routeChanged = new BehaviorSubject<RouteChanged>({ prevRoute: '/', currentRoute: '/' }); 

    constructor() { 
    } 
} 

app.component.ts(您根组件)

... 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent implements OnInit, OnDestroy { 
    private subscriptions = new Subscription(); 

    constructor(private eventsService: EventsService) { 
      this.subscriptions.add(this.router.events 
       .filter(event => event instanceof NavigationEnd) 
       .pairwise() 
       .subscribe(navigationEvents => { 
        const prevPage = <NavigationEnd>navigationEvents[0]; 
        const currentPage = <NavigationEnd>navigationEvents[1]; 
        this.eventsService.routeChanged.next(
         { prevRoute: prevPage.urlAfterRedirects, currentRoute: currentPage.urlAfterRedirects }); 
       })); 
     } 

    ngOnDestroy(): void { 
     this.subscriptions.unsubscribe(); 
    } 

    ... 
} 

您的目标-route.ts

... 
constructor(private eventsService: EventsService) { 
    this.subscriptions.add(this.eventsService.routeChanged.subscribe((routeChanged) => { 
     // use routeChanged.prevRoute and routeChanged.currentRoute here... 
    })); 
} 

P.S.在服务中使用BehaviorSubjectReplaySubject非常重要,以便在页面加载后您的子组件订阅时获得正确的以前的路由事件。

答案已经给出:当组件注册它时,NavigationEnd事件已经引发。我不喜欢“Dimitar Tachev”的想法,通过通过主题代理这些事件来创建解决方法。 在我的情况下,解决方案是:

  1. 让Component像以前一样订阅NavigationEnd事件。
  2. 使组件从ngOnInit方法中的注入路由对象中加载初始状态。

最后,另一种解决方案是将订阅路由更改事件移动到组件的构造函数中。