【问题标题】:subscribe route params in a component outside of router outlets component在路由器出口组件之外的组件中订阅路由参数
【发布时间】:2018-08-01 08:58:04
【问题描述】:

我有一个工具栏组件在路由器插座上方对齐。路由器插座具有表格和图表等各种组件。

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

我想从不属于插座的工具栏组件访问路由参数。 (捕获当前路径以在工具栏上显示路径名称)

主要组件:

  <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 }
       }
     }

【问题讨论】:

    标签: angular angular-routing angular-router angular-router-params


    【解决方案1】:

    您需要使用route.firstChildroute.children 来实现它,方法与使用参数相同。

    【讨论】:

      【解决方案2】:

      &lt;app-toolbar&gt; 所在的 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 中的第二种方法的启发

      【讨论】:

        【解决方案3】:

        修改你的工具栏组件为

        工具栏组件:

            this.router.events.subscribe((val) => {
              if (val instanceof NavigationEnd) {
                let r = this.route;
                while (r.firstChild) {
                  r = r.firstChild;
                }
                r.params.subscribe((params) => {
                  this.healthStatus(params);
                });
              }
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-14
          • 2020-12-30
          • 2016-07-06
          • 2017-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-12
          相关资源
          最近更新 更多