Passing data through Angular2 router

本小妞迷上赌 提交于 2019-11-30 01:53:52

See https://angular.io/guide/router for an in-depth example. Scroll down to this code snippet:

gotoHeroes(hero: Hero) {
  let heroId = hero ? hero.id : null;
  // Pass along the hero id if available
  // so that the HeroList component can select that hero.
  // Include a junk 'foo' property for fun.
  this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}

To get the value of 'id' in the target component:

ngOnInit() {
  this.heroes$ = this.route.paramMap.pipe(
    switchMap((params: ParamMap) => {
      // (+) before `params.get()` turns the string into a number
      this.selectedId = +params.get('id');
      return this.service.getHeroes();
    })
  );
}
ammy

I hope this will work. Try using Query Parameters.

 <nav>
      <a [routerLink]="['/component1']">No param</a>
      <a [routerLink]="['/component2']" [queryParams]="{ page: 99 }">Go to Page 99</a>
 </nav>

or

opencomponent2(pageNum) {
    this.router.navigate(['/component2'], { queryParams: { page: pageNum } });
  }

In child component :

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

  ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        // Defaults to 0 if no query param provided.
        this.page = +params['page'] || 0;
      });
  }

I have studied this on rangle.io website. Try this if it works for you. otherwise https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service is only option.

Unless you want users to manipulate the query string in the addressbar, do a "atob" and "btoa" before sending and after receiving the data. Just a little security

Also, if you don't want to have a subscription, you can use the Route snapshot param as follows (just that it doesn't keep on updating like an observable, so unless the component gets re-init, it won't be getting updated value if any. Hence a good place to get the value is in the ngOnInit event handler

// before
this._router.navigate(["/welcome/" + atob(userName)]);

// after
ngOnInit() {
    this.userName = btoa(this.route.snapshot.params['userName']);
}

You can pass data using router, for example

{ path: 'form', component: FormComponent ,data :{data :'Test Data'} },

and your component

import { ActivatedRoute, Router } from '@angular/router';

export class FormComponent {
    sub: any;
    constructor(private route: ActivatedRoute) { }
    ngOnInit() {
        this.sub = this.route
            .data
            .subscribe(value => console.log(value));
    }
}

More info

But this may not be the preferred way, you can use parent child communication or make a service common and share data between them. Check below references for doing that.

Parent child communication

Share data using service

sender html

<a [routerLink]="['../../../print/attendance/',{data:userDetails | json}]">link</a>

receiver ts
ngOnInit() {
   this.route.params.subscribe(params=>
    {
      this.data=JSON.parse(params['data'])
    }
    );

  }
this.router.navigate(['path', { flag: "1"}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!