Retrieving a data property on an Angular2 route regardless of the level of route nesting using ActivatedRoute

后端 未结 3 1523
醉梦人生
醉梦人生 2021-02-05 08:51

I have defined a number of routes as follows:

export const AppRoutes: Routes = [
  {path: \'\', component: HomeComponent, data: {titleKey: \'homeTitle\'}},
  {pa         


        
3条回答
  •  忘了有多久
    2021-02-05 09:46

    We had this same problem. We decided to go about it another way. Instead of trying to listen for the data emits on the ActivatedRoute, we subscribe to the events Observable on the router itself:

    import { Component } from "@angular/core";
    import { NavigationEnd, Router } from "@angular/router";
    
    declare var module: any;
    
    @Component({
        moduleId: module.id,
        selector: "app-layout",
        templateUrl: "main-layout.component.html"
    })
    export class LayoutComponent {
        titleKey: string;
    
        constructor(private router: Router){}
    
        ngOnInit() {
            this.router.events
                .filter((event: any) => event instanceof NavigationEnd)
                .subscribe(() => {
                    var root = this.router.routerState.snapshot.root;
                    while (root) {
                        if (root.children && root.children.length) {
                            root = root.children[0];
                        } else if (root.data && root.data["titleKey"]) {
                            this.titleKey = root.data["titleKey"];
                            return;
                        } else {
                            return;
                        }
                    }
                });
        }
    }
    

    Note that we're using the value in a component that is used at the top level but needs the data from the deepest child route. You should be able to pretty easily convert this to a service that emits events whenever the titleKey changes value.

    Hope this helps.

提交回复
热议问题