我的页面中有一个子导航,它在一个公共(public)主视图下方显示一些 subview 。我想通过 <router-outlet>
将对象传递给 subview 这样我就可以在主组件中检索一次数据,然后与我的子组件共享。
注意:如果我包含指令 <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>
subview 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'};
}
subview 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>
然后在你的 subview 中
@Component({
selector: 'one',
directives: [CORE_DIRECTIVES],
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];
}
}
如何注入(inject)服务:
export class Cars {
constructor(cars:CarsService) {
this.cmpList1 = cars.list1;
this.cmpList2 = cars.list2;
}
}
这样您就可以使用该服务进行通信,而无需考虑父/子或其他奇怪的限制。
关于typescript - Angular2 将@Inputs 与<router-outlet> 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34363792/