5

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?

smartmouse
  • 13,912
  • 34
  • 100
  • 166

1 Answers1

7

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thank you for your reply! So what is the difference between using `resolve` and invoking `service` from components that need it? – smartmouse Oct 21 '16 at 12:23