【问题标题】:Angular Passing Data Between Routes路由之间的角度传递数据
【发布时间】:2018-09-14 19:45:01
【问题描述】:

我在使用 Angular 4 中的路由时遇到了一点问题。你知道,当我尝试使用 navigate('root', data) 将数据从一个组件传递到另一个组件时,我刚刚收到了 [object Object],[object Object],[object Object]

组件

export class FillRequestComponent implements OnInit {

  constructor(private route: Router, private dataRoute: ActivatedRoute) { }

  ngOnInit() {
    const key: Products = this.dataRoute.snapshot.params['objectProducts'];
    console.log(key);
  }

界面

export interface Products {

  color: string,
  question: string,
  surname: string,
  icon: string,
  selected: boolean,
  transparent: boolean
}

发送方法

const data = {
      category: this.optionSelected,
      objectProducts: this.optionSelected === 'CREDIT' ? this.productCreditList :
        this.productAccountsList
    };

    this.route.navigate(['/requests/fill', data]);

【问题讨论】:

  • 我发现通过路线传递对象不是一种友好的模式,因为拥有路线的主要目的是让用户可以直接在那里导航。如果他们直接在那里导航,父母仍然能够传递对象吗?通常不会。

标签: angular angular-router


【解决方案1】:

在当前版本中,现在可以在 @angular/router 中使用它。

Angular 7.2 将路由状态引入NavigationExtras,它采用类似于queryParams 等的对象字面量。

状态可以强制设置:

this.router.navigate(['example'], { 
  state: { example: 'data' } 
});

或以声明方式:

<a routerLink="/example" [state]="{ example: 'data' }">
  Hello World
</a>

并使用以下方法读入顶级组件

this.router.getCurrentNavigation().extras.state;

或在子组件中使用:

window.history.state

添加了一个在StackBlitz上使用的工作示例

【讨论】:

  • navigate(commands: any[], extras?: NavigationExtras) /example 应该作为列表发送吗?
  • 链接:Stackblitz 请您检查一下这不起作用
  • 我知道了,必须在constructor中提及
  • 将此行移至构造函数有效! this.name = this.router.getCurrentNavigation().extras.state.example;
  • 有谁知道为什么this.router.getCurrentNavigation().extras.state 在子组件中不起作用?
【解决方案2】:

当您将对象作为路由参数传递时,它会导致对该对象调用 toString 并从该对象中获得结果 [object Object]

const obj = {};
console.log(obj.toString());

如果要传递复杂类型,则需要将stringify 传递给string 并作为string 传递。得到后,需要再次解析成对象。

this.route.navigate(['/requests/fill', JSON.stringify(data)]);

稍后访问

const key: Products = JSON.parse(this.dataRoute.snapshot.params['objectProducts']);

【讨论】:

  • 我认为这不是一种可扩展的做事方式,将所有这些数据放在 URL 中,用于字符串化然后解析......似乎不是解决这个问题的正确方法。跨度>
【解决方案3】:

你不能在参数中传递数据列表

所以你需要将对象列表转换成字符串然后通过

navigate('root',   JSON.stringify(data))

然后在得到这个的时候进行解析

const key: Products =JSON.parse(this.dataRoute.snapshot.params['objectProducts']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    相关资源
    最近更新 更多