How do I pass data to Angular routed components? How do I pass data to Angular routed components? angular angular

How do I pass data to Angular routed components?


update 4.0.0

See Angular docs for more details https://angular.io/guide/router#fetch-data-before-navigating

original

Using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.

See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

The router shipped with RC.4 re-introduces data

constructor(private route: ActivatedRoute) {}
const routes: RouterConfig = [  {path: '', redirectTo: '/heroes', pathMatch : 'full'},  {path : 'heroes', component : HeroDetailComponent, data : {some_data : 'some value'}}];
class HeroDetailComponent {  ngOnInit() {    this.sub = this.route      .data      .subscribe(v => console.log(v));  }  ngOnDestroy() {    this.sub.unsubscribe();  }}

See also the Plunker at https://github.com/angular/angular/issues/9757#issuecomment-229847781


I think since we don't have $rootScope kind of thing in angular 2 as in angular 1.x. We can use angular 2 shared service/class while in ngOnDestroy pass data to service and after routing take the data from the service in ngOnInit function:

Here I am using DataService to share hero object:

import { Hero } from './hero';export class DataService {  public hero: Hero;}

Pass object from first page component:

 ngOnDestroy() {    this.dataService.hero = this.hero;  }

Take object from second page component:

 ngOnInit() {    this.hero = this.dataService.hero;  }

Here is an example: plunker


Angular 7.2.0 introduced new way of passing the data when navigating between routed components:

@Component({  template: `<a (click)="navigateWithState()">Go</a>`,})export class AppComponent  {  constructor(public router: Router) {}  navigateWithState() {    this.router.navigateByUrl('/123', { state: { hello: 'world' } });  }}

Or:

@Component({  selector: 'my-app',  template: `  <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>`,})export class AppComponent  {}

To read the state, you can access window.history.state property after the navigation has finished:

export class PageComponent implements OnInit {  state$: Observable<object>;  constructor(public activatedRoute: ActivatedRoute) {}  ngOnInit() {    this.state$ = this.activatedRoute.paramMap      .pipe(map(() => window.history.state))  }}