Passing dynamic data through Angular 2 route
You can use a resolver. The data returned by a resolver is made available to routes the same way static data
on route configurations is
For an example see https://angular.io/guide/router#resolve-guard
@Injectable() export class CrisisDetailResolve implements Resolve<Crisis> { constructor(private cs: CrisisService, private router: Router) {} resolve(route: ActivatedRouteSnapshot): Promise<Crisis>|boolean { let id = route.params['id']; return this.cs.getCrisis(id).then(crisis => { if (crisis) { return crisis; } else { // id not found this.router.navigate(['/crisis-center']); return false; } }); } }
path: '', component: CrisisListComponent, children: [ { path: ':id', component: CrisisDetailComponent, canDeactivate: [CanDeactivateGuard], resolve: { crisis: CrisisDetailResolve } },
ngOnInit() { this.route.data .subscribe((data: { crisis: Crisis }) => { this.editName = data.crisis.name; this.crisis = data.crisis; }); }
You can do two things 1.Not recommended but use data as router parameter and pass,
{ path: 'some:data', component: SomeComonent }
and use as
let data = {"key":"value"}
this.router.navigate(['/some', data)
2.Instead of passing data through route params(because data may be huge and also vulnerable to attack since it can be viwed by the user)
@Injectable()
export class SomeService {
data = {};
}
@Component({...
providers: [SomeService]
export class Parent {
constructor(private someService:SomeService) {}
private click() {
this.someService.data = {"key":"value"}
}
}