首页 文章

在路由器出口组件之外的组件中订阅路由参数

提问于
浏览
1

我在路由器插座上方有一个工具栏组件 . 路由器插座有各种组件,如表格和图表 .

能够在使用路由器插座显示的任何组件中订阅路由参数 .

我想从工具栏组件访问路径参数,这不是插座的一部分 . (捕获当前路径以显示工具栏上的路径名称)

主要成分:

<app-toolbar> </app-toolbar>
  <router-outlet> </router-outlet> // shows either a table or chart component

工具栏组件:

export class ToolbarComponent {
   constructor(private route: ActivatedRoute) {
      this.route.subscriber(params => 
          { console.log(params) //param is empty }
   }
 }

表组件:

export class TableComponent{
       constructor(private route: ActivatedRoute) {
          this.route.subscriber(params => 
              { console.log(params) //param has data }
       }
     }

2 回答

  • 1

    你需要使用 route.firstChildroute.children 来实现它,就像使用params一样 .

  • 1

    <app-toolbar> 所在的MainComponent中,您可以添加:

    path$: Observable<String>;
    
    constructor( private router: Router ) {
      this.path$ = this.router.events.pipe(
        filter(event => event instanceof RoutesRecognized),
        map((event: RoutesRecognized) => {
          return event.state.root.firstChild.url.join('/');
        }));
    }
    

    然后在html模板中,您可以编写如下内容:

    <app-toolbar>{{ path$ | async }}</app-toolbar>
    

    这是受到第二种方法的启发https://stackoverflow.com/a/46697826/9423231

相关问题