【问题标题】:send data to another component through route in angular [duplicate]通过角度路由将数据发送到另一个组件[重复]
【发布时间】:2020-04-11 01:14:58
【问题描述】:

我正在开发一个 Angular 应用程序,并意识到在最新版本的 Angular 中,数据可以通过路由将一个组件传输到另一个组件。我浏览了一些博客,但我不太清楚如何做到这一点。

我的代码

component1.ts

sendMessageto2() {
    par = this.param
    this.router.navigate(['/vav'],{state : {data : {par}}})
    console.log(this.param)
  }

我想将变量this.param 传递给component2

component1.html

<area shape="rect" coords="818,232,917,262" (click)="sendMessageto2()">

component2.ts

ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
    .pipe(map(() => window.history.state))  
  }

我不确定如何在 component2 中获取此数据。我收到 map 的错误。找不到地图。有人可以帮我吗?

谢谢

【问题讨论】:

标签: angular routing angular7-router


【解决方案1】:

我假设您尝试传递的数据是一个字符串。像这样定义你的路线,

const routes: Routes = [
  { path:'', component : C1Component },
  { path:'vav', component : C2Component },
];

路由时,将URL中的值添加为queryParams

let navigationExtras: NavigationExtras = {
    queryParams: {
        "data"   : encodeURIComponent('Your data'),
    }
};

this.router.navigate(["vav"], navigationExtras);

使用ActivateRoute获取第二个组件中的queryParams

decodeURIComponent(this.route.snapshot.queryParams['data']);

演示:https://stackblitz.com/edit/angular-5zw742

如果数据是一个对象,编码前JSON.stringify()它,解码后JSON.parse()它。

【讨论】:

  • '(params: ParamMap) => void' 类型的参数不可分配给'(value: ParamMap, index: number) => ObservableInput' 类型的参数。类型 'void' 不可分配给类型 'ObservableInput'
  • params 出现错误
  • 我用queryParams 让它变得更简单了。检查更新的答案和演示。
【解决方案2】:

为了传递数据,您可以这样做

this.router.navigate(["/vav", { 'data': data }]);

用于在其他页面接收

constructor(public router: Router, public route: ActivatedRoute){}
route.params.subscribe(params => {
        let data = params['data']
    });

【讨论】:

  • route 还是router
  • @cvg 感谢您指出我忘了添加公共路线:ActivatedRoute。
  • 我也应该在app-routing.module.ts 中进行一些更改吗?
  • 不需要。它用于获取参数值。
【解决方案3】:

你可以这样传递:

routing.ts

{path: 'component2', component: YourComponent2} // configure it in the routing file

component1.ts

private router: Router // import router
this.router.navigate(['/component2', {id: '1', name: 'surjeet'}]);

component2.ts

private route: ActivatedRoute // import ActivatedRoute
this.route.snapshot.paramMap.get('id');
this.route.snapshot.paramMap.get('name');

【讨论】:

    【解决方案4】:

    试试这个

    在组件 2 上

    ngOnInit() {
        this.state$ = this.route.snapshot.paramMap.get('param') ; 
      }
    
    

    'param' value 是从组件 1 添加到 url 的值。

    【讨论】:

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