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

后端 未结 3 1519
醉梦人生
醉梦人生 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:37

    Update

    You may try below in AppComponent ,

       constructor(private translate: TranslateService,
              private sessionService: SessionService,
              private titleService: Title,
              private activatedRoute: ActivatedRoute) {
    
          this.router.events.subscribe((arg) => {
             if(arg instanceof NavigationEnd) { 
               console.log(this.getTitle(this.activatedRoute.snapshot));
             }
          });
       }
    
       getTitle = (snapshot) => {
         if(!!snapshot && !!snapshot.children && !!snapshot.children.length > 0){
          return this.getTitle(snapshot.children[0]);
         }
        else if(!!snapshot.data && !!snapshot.data['titleKey']){
          return snapshot.data['titleKey'];
        }
        else{
          return '';
        }
       }
    

    seems little hacky but works.

    Old

    You may try below,

    {
      path: 'conversation/:otherId', 
      component: MessageConversationComponent, 
      data: {titleKey: 'XXX'},
      // add below resolve
      resolve: {
                titleKey: MessageConversationResolve
      }      
    }
    

    add a new service MessageConversationResolve.ts and add it appropriately in providers.

    import { Injectable } from '@angular/core';
    import { Router, Resolve,ActivatedRouteSnapshot } from '@angular/router';
    import { Observable }             from 'rxjs/Observable';
    
    @Injectable()
    export class AdminDetailResolve implements Resolve {
      constructor(private router: Router,
                  private titleService: Title) {}
    
      resolve(route: ActivatedRouteSnapshot): Observable | Promise | any {
        // route.data will give you the titleKey property
        // console.log(route.data);
        // you may consume titleService here to setTitle
    
        return route.data.titleKey;
     }
    }
    

    Below is angular version which supports above solution,

    Angular 2 version : 2.0.0-rc.5

    Angular Router version : 3.0.0-rc.1

提交回复
热议问题