我的页面中有一个子导航,在公共主视图下方显示一些子视图.我想通过< router-outlet>将对象传递给子视图.这样我就可以在主组件中检索一次数据,然后与我的子组件共享它.
注意:如果我包含指令< one>< / one>在main.html它可以工作,但这不是我想要的行为.
主要观点:
- <h1>Details</h1>
- <a [router-link]="['./sub1']">One</a> |
- <a [router-link]="['./sub2']">Two</a> |
- <a [router-link]="['./sub3']">Three</a>
- <hr/>
- <router-outlet [data]="maindata"></router-outlet>
子视图1:
- <h2>{{ data.name }}</h2>
- ...
主要观点:
- @Component({
- selector: 'main-detail',directives: [ROUTER_DIRECTIVES],templateUrl: './main.html'
- })
- @RouteConfig([
- { path: '/',redirectTo: '/one' },{ path: '/one',as: 'One',component: OneComponent },{ path: '/two',as: 'Two',component: TwoComponent },{ path: '/three',as: 'Three',component: ThreeComponent }
- ])
- export class MainComponent {
- maindata: Object = {name:'jim'};
- }
子视图1:
- @Component({
- selector: 'one',directives: [CORE_DIRECTIVES],inputs: ['data'],templateUrl: './one.html'
- })
- export class OneComponent {
- @Input() data;
- }
如果它是简单数据,您可以通过
RouteParams传递它们
- <a [router-link]="['./sub3'],{name:'jim'}">Three</a>
然后在你的子视图中
- @Component({
- selector: 'one',templateUrl: './one.html'
- })
- export class OneComponent {
- data: any;
- constructor(params: RouteParams){
- this.data = params.get('data');
- }
- }
您还可以设置路由以始终通过将组件中的RouterConfig移动来从组件传递参数(注意,这不是通常的方式):
- export class AppCmp {
- history: string[] = [];
- constructor(public list: PersonalizationList,private router_: Router) {
- list.get('histoy',(response) => {
- this.history = response;
- });
- router_.config([
- { path: '/',component: HomeCmp,as: 'Home',data: this.history },{ path: '/about',component: AboutCmp,as: 'About' }
- ]);
- }
- }
如果您打算做一些更复杂的事情,我建议使用服务在路由/组件之间进行通信.这实际上是我喜欢的方式.
样品服务:
- import {Injectable} from 'angular2/angular2';
- @Injectable()
- export class CaRSService {
- list1: array<any> = ['a','b','c','d'];
- list2: array<any>;
- constructor() {
- this.list2 = [1,2,3,9,11];
- }
- }
如何注入服务:
- export class Cars {
- constructor(cars:CaRSService) {
- this.cmpList1 = cars.list1;
- this.cmpList2 = cars.list2;
- }
- }
这样,无论父/子或其他奇怪的限制,您都可以使用该服务进行通信.