【问题标题】:How do I pass data from angular component to another component via router?如何通过路由器将数据从角度组件传递到另一个组件?
【发布时间】:2019-10-10 18:06:51
【问题描述】:

我试图通过以下方式将数据从角度组件传递到另一个组件 路由器。任何优雅的解决方案?

我试过了,效果很好。

this.router.config.forEach(route => {
    if (route.path === 'pages') {
        route.children.forEach((child) => {
            if (child.path === 'saveName') {
                child.data = {
                    name: "Jack"
                };
            }
        });
    }
});

this.router.navigate(['/pages/saveName']);

并且还发送一个带有数据的文件。

只想知道是否有更优雅的解决方案,比如 下面一个。

this.router.navigate(['/pages/saveName'],{"name":"Jack"});

【问题讨论】:

  • 您使用的是哪个版本的 Angular?
  • 我正在使用 Angular 7

标签: angular


【解决方案1】:

是的,请查看documentation

this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);

【讨论】:

  • 我们试图发送一个文件但是这个方法数据传递抛出 URL,对吧?
  • 使用路由策略,只能在URL中作为查询参数传递。使用 @Input 装饰器将数据从一个组件传递到另一个组件。
  • @input 装饰器只能与相关组件一起使用吗?即父子
【解决方案2】:

我认为是更好的解决方案。检查以下链接。

https://angular.io/guide/router#fetch-data-before-navigating

【讨论】:

    【解决方案3】:

    Angular 7.2 支持在导航期间通过状态对象传递数据

    您可以在 navigateByUrl 方法中传递状态对象

    this.router.navigateByUrl('/path', { state: { hello: 'world' } });
    

    使用 routerLink 指令传递数据

    <a routerLink="/path" [state]="{ hello: 'world' }">Go</a>`
    

    并使用 paramMap Observabele 读取数据以仅过滤 window.history.state

     constructor(public activatedRoute: ActivatedRoute) {}
    
      ngOnInit() {
        this.state$ = this.activatedRoute.paramMap.pipe(
          map(() => window.history.state)
        );
      }
    

    查看此链接:https://netbasal.com/set-state-object-when-navigating-in-angular-7-2-b87c5b977bb

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2018-10-18
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      相关资源
      最近更新 更多