【问题标题】:Angular 6 - How to access route resolved data from non routed componentsAngular 6 - 如何从非路由组件访问路由解析数据
【发布时间】:2018-07-04 14:57:39
【问题描述】:

我正在使用 Angular 6,并且有一个非路由组件需要从我正在导航到的路由访问已解析的数据。

阅读我认为我需要利用路由器事件来让我的组件知道 NavigationEnd 事件何时发生。

到目前为止,我的 ngOnInit() 中有这个:

this.router.events.pipe(
  filter(event => event instanceof NavigationEnd)
  ).subscribe((route: ActivatedRoute) => {
      console.log(route);
  });

但是当我在控制台中查看输出时,我只得到如下几个属性:

NavigationEnd {id: 2, url: "/trip-schedule", urlAfterRedirects: "/trip-schedule"}

我还注意到,只有当我使用绑定到 routerLink 的元素导航到某个状态时才会触发此事件。如果我在路由器实例本身上调用 navigate(),我看不到任何输出记录。

我应该以不同的方式解决这个问题吗?

谢谢

【问题讨论】:

  • 如果它不是一个路由组件,它不应该尝试从路由访问任何东西,恕我直言。为什么不将数据作为路由组件的输入传递?还是将数据存储在路由组件内部的一个服务中,然后在这个非路由组件中从服务中获取?
  • 我只是在你所说的之后再考虑一下 - 所以我的路线有一个解决方案,它调用我在我的应用程序中拥有的 http 服务。我想我可以在这个服务中使用一个主题并在我的非路由组件中订阅它,然后仍然能够访问我在路由组件中解析的数据。这看起来是一种合乎逻辑的方法吗?

标签: angular


【解决方案1】:

路由数据可以从ActivatedRoute读取为:

    @Component({
      selector: 'app-root',
      template: `<router-outlet></router-outlet>`,
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent   {

    constructor(private route: ActivatedRoute, private router: Router,) {

       this.router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe((route: ActivatedRoute) => {
          console.log(route);
          console.log(this.route.snapshot.firstChild.data);
       });

    }

但是使用此解决方案,您必须使用一些访问器 root、firstChild、children、parent 等知道您有趣的 ActivatedRoute 的深度和位置... 我的例子被简化了。

【讨论】:

    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2017-06-28
    • 2016-04-14
    • 2017-03-06
    相关资源
    最近更新 更多