0

To start with: The application I build at the moment is an Angular2(RC3) one (with the @angular/routerv3.0.0-alpha.8 module).

This app consists of a parent component including different header components which should be selected according to the current route. In short:

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

In the parent components template there is a switch which looks like:

<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>

Where dataStore in the parent component is defined as:

private dataStore: {
    currentRoute: string
};

All my efforts so far didn't result in a working solution. I tried to create a routeStore which provides a custom Observable and looks like this:

@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);
    }
}

This part is able to provide data to the parent when I navigate to another route via a button click like:

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

But as soon as I refresh the page or initialize the app it throws the

Expression has changed after it was checked.

error.

Also my effort to handle all routing changes inside the parent component only by using the router like

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

didn't result in an acceptable result, as the path property of the urlPathArray is always returning an empty string (meaning the route of the parent component).

How can I get the currently active route to be passed to the parent components dataStore objects currentRoute property to rerun the ngSwitch statement and display the correct header?

4

1 回答 1

1

这可以使用路由器事件来处理。添加对NavigationEnd对象的事件检查的订阅并将您的逻辑移到那里

router.events.subscribe(e => { 
    if (e instance of NavigationEnd) 
    {
        ///your logic 
    }
});
于 2016-06-29T10:29:46.667 回答