How to get current route custom data in angular 2?

后端 未结 11 1843
旧时难觅i
旧时难觅i 2020-12-05 06:21

I have set up routes is like below

const appRoutes: Routes = [
  {
    path: \'login\',
    component: LoginComponent,
    data: {
      title: \'Login TTX\         


        
11条回答
  •  Happy的楠姐
    2020-12-05 07:15

    For those that are now using Angular 6+ and latest RXJS 6 here is something based on the ansers above:

    Routing example:

    const routes: Routes = [
      {path: 'home', component: HomeComponent, data: {title: 'Home'}},
      // {path: '', redirectTo: 'home', pathMatch: 'full'},
      {path: 'login', component: LoginComponent, data: {title: 'Login'}},
      {path: 'dashboard', component: DashboardComponent, data: {title: 'Dashboard'}, canActivate: [AppAuthGuard]},
      {path: 'eventDetails', component: EventCardComponent, data: {title: 'Details'}},
      {path: '**', redirectTo: 'home', pathMatch: 'full'},
    ];
    

    How to get the title example:

    ngOnInit() {
        this.routerEventSubscription = this.router.events
          .pipe(filter(event => event instanceof RoutesRecognized))
          .pipe(map((event: RoutesRecognized) => {
            return event.state.root.firstChild.data['title'];
          })).subscribe(title => {
            this.title = title;
          });
      }
    

提交回复
热议问题