How do I pass data to Angular routed components?

Update 4.0.0

See Angular Angular Router – Fetch data before navigating for more details.

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 Angular Angular Cookbook Component Communication – 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.

Leave a Comment