我看到有两种方法可以将简单数据(例如字符串)从路由路径传递到不同的组件:
第一种方式:
路由端:
export const AppRoutes: Routes = [
...
{
path: '/one', component: OneComponent, resolve: { foo: 'foo' }
}
];
组件方面:
@Component()
export class OneComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.foo = this.route.snapshot.data['foo'];
}
}
第二种方式:
路由端:
const routes: RouterConfig = [
...
{
path: '/one', component: OneComponent, data : {some_data : 'some value'}
}
];
组件方面:
@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();
}
}
那么将值传递给组件的最佳方式是什么?resolve
和data
属性有什么区别?