Search code examples
angularparameterscomponentsangular2-routingangular2-router

Angular2: what is difference between resolve and data in routing paths?


I see that are 2 ways to pass simple data, such as strings, to different components from routing paths:

First way:

Routing side:

export const AppRoutes: Routes = [
  ...
  { 
    path: '/one', component: OneComponent, resolve: { foo: 'foo' }
  }
];

Component side:

@Component()
export class OneComponent implements OnInit {
    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.foo = this.route.snapshot.data['foo'];
    }
}

Second way:

Routing side:

const routes: RouterConfig = [
    ...
    {
      path: '/one', component: OneComponent, data : {some_data : 'some value'}
    }
];

Component side:

@Component()
export class OneComponent implements OnInit {
    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.obs = this.route
          .data
          .subscribe(v => console.log(v));
    }

    ngOnDestroy() {
        this.obs.unsubscribe();
    }
}

So which is the best way to pass values to components? What are the differences between resolve and data properties?


Solution

  • data is static data added to the route, while resolve calls a service that can calculate data, also using async calls.

    Your resolve example is invalid.

    See https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard