簡體   English   中英

Angular2:提供到父組件的當前路由

[英]Angular2: provide current route to parent component

首先,我目前構建的應用程序是Angular2(RC3)(帶有@ angular / routerv3.0.0-alpha.8模塊)。

該應用程序由一個父組件組成,該父組件包括應根據當前路由選擇的不同標頭組件。 簡而言之:

route: localhost:4200/login => display login header component,
route: localhost:4200/home => display home header component etc.

在父組件模板中,有一個開關,如下所示:

<span [ngSwitch]="dataStore.currentRoute">
    <span *ngSwitchCase="'/login'"><login-header></login-header></span>
    <span *ngSwitchCase="'/home'"><home-header></home-header></span>
</span>
<div class="content"><router-outlet></router-outlet></div>
<app-footer></app-footer>

父組件中的dataStore定義為:

private dataStore: {
    currentRoute: string
};

到目前為止,我所有的努力都沒有找到可行的解決方案。 我試圖創建一個提供自定義Observable的routeStore,如下所示:

@Injectable()
export class RouteStore {
    private dataStore: {
        currentRoute: string
    };
    private _currentRoute$: BehaviorSubject<string>;

    constructor(private routeHelper: RouteHelperService) {
        this.dataStore = {currentRoute: this.routeHelper.getCurrentBaseRoute()};
        this._currentRoute$ = <BehaviorSubject<string>>new BehaviorSubject(this.dataStore.currentRoute);
    }

    get currentRoute$() {
        return this._currentRoute$.asObservable();
    }

    public updateCurrentRoute() {
        this.dataStore = {currentRoute: this.routeHelper.getCurrentBaseRoute()};
        this._currentRoute$.next(this.dataStore.currentRoute);
    }
}

當我通過以下按鈕單擊導航到另一條路線時,該部分能夠向父級提供數據:

userIconClick(userName: string) {
    this.router.navigate(['/home', userName]).then(() => this.routeStore.updateCurrentRoute());
  }

但是,只要我刷新頁面或初始化應用程序,它就會拋出

Expression has changed after it was checked.

錯誤。

我也只能通過使用路由器來處理父組件內部的所有路由更改

this.route.url.subscribe(urlPathArray => this.dataStore.currentRoute = '/' + urlPathArray[0].path);

不會產生可接受的結果,因為urlPathArray的path屬性始終返回一個空字符串(表示父組件的路由)。

如何獲取當前活動的路由以傳遞給父組件dataStore對象的currentRoute屬性,以重新運行ngSwitch語句並顯示正確的標頭?

這可以使用路由器事件來處理。 添加對事件的預訂,檢查NavigationEnd對象,並在其中移動邏輯

router.events.subscribe(e => { 
    if (e instance of NavigationEnd) 
    {
        ///your logic 
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM