Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dynamic data through Angular 2 route

It is possible to pass static data to an Angular 2 route without showing it on the URL.

But how can I pass dynamic data/object in the same way?

like image 368
Kaleab Avatar asked Dec 12 '16 06:12

Kaleab


1 Answers

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;
    });
}
like image 180
Günter Zöchbauer Avatar answered Oct 10 '22 01:10

Günter Zöchbauer