2017-04-05 85 views
9

我從一個組件路由到另一個組件。一旦路線完成,我想使用以前的路線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

回答

-1

我只是偶然發現了同樣的問題,並找到了它的原因:訂閱路由器事件的服務從來沒有像依賴注入器那樣實例化,因爲服務沒有在該路由注入。

一個服務似乎只在被注入某個地方時纔會立即執行。

因此,如果整個代碼(不是事件)被調用,那麼檢查你的第一個路由。

1

我有完全相同的情況,我發現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非常重要,以便在頁面加載後您的子組件訂閱時獲得正確的以前的路由事件。

0

答案已經給出:當組件註冊它時,NavigationEnd事件已經引發。我不喜歡「Dimitar Tachev」的想法,通過通過主題代理這些事件來創建解決方法。 在我的情況下,解決方案是:

  1. 讓Component像以前一樣訂閱NavigationEnd事件。
  2. 使組件從ngOnInit方法中的注入路由對象中加載初始狀態。

最後,另一種解決方案是將訂閱路由更改事件移動到組件的構造函數中。