通过 angular 中的路由将数据发送到另一个组件

send data to another component through route in angular

我正在开发一个 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 的错误。找不到 map.Can 有人帮我解决这个问题?

谢谢

You can pass like this:

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');

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

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

If the data is an object, JSON.stringify() it before encoding and JSON.parse() it after decoding.

要传递数据,你可以这样做

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

用于在其他页面接收

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

试试这个

在组件 2 上

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

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