首页 文章

Angular2:提供父组件的当前路由

提问于
浏览
0

首先:我现在构建的应用程序是一个Angular2(RC3)(使用@ angular / routerv3.0.0-alpha.8模块) .

此应用程序包含一个父组件,包括不同的 Headers 组件,应根据当前路由选择 . 简而言之:

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 objects currentRoute 属性以重新运行ngSwitch语句并显示正确的标头?

1 回答

  • 1

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

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

相关问题