背景
假设我有一些父组件,称之为 MatchList
,它提供了一个 Hero
对象的列表,以及其他内容 . 每个 Hero
对象都具有某些表中显示的属性 . 现在假设我还为每个 Hero
都有一个按钮,用于更新路径,加载新视图以及显示更多详细信息 .
之前
http://heroic.com/match-list
后
http://heroic.com/hero-84
问题
我的问题至关重要:我想从我的 MatchList
模板中的按钮调用路由器的 navigate()
方法,但是当我尝试这样做时收到以下错误:
EXCEPTION:评估“click”时出错BrowserDomAdapter.logError @ ... angular2.dev.js:21835 ORIGINAL EXCEPTION:TypeError:l_context.setPath不是函数... angular2.dev.js:21835 TypeError:l_context . setPath不是...的函数
In other words 看起来我无法在子模板中引用父组件的路由器方法 .
那么,对于子组件访问父组件(或“上下文”)的方法,Angular 2中的正确和最佳方法是什么?
如果解决方案更清洁,我更愿意
class parent {
child: Child;
constructor(...) {
...
this.child.parent = this;
}
}
示例代码
EDIT 我将模板按钮更改为
(^click)="setPath(match.match_id)"
我不再收到错误消息,但没有任何反应 - 我甚至没有得到确认点击的控制台日志 .
到目前为止我所拥有的片段 .
//父
@Component({
selector: 'dota-app',
directives: [Home, MatchesView, ROUTER_DIRECTIVES],
templateUrl: 'AppView.html'
})
@RouteConfig([
{ path: '/', component: Home, as: 'Home' },
{ path: '/matches', component: MatchesView, as: 'Matches' },
{ path: '/match-details', component: MatchDetailsView, as: 'MatchDetails'}
])
export class RootDotaComponent {
router: Router;
constructor(router: Router) {
this.router = router;
}
public setPath(linkParams: any[]|string): void {
if (typeof linkParams === "string")
linkParams = [linkParams];
this.router.navigate(<any[]>linkParams);
}
}
}
//儿童
@Component({
selector: 'matches-view',
providers: [DotaRestDao],
})
@View({
templateUrl: './components/MatchesView/MatchesView.html',
directives: [CORE_DIRECTIVES]
})
export class MatchesView {
public result;
private dataService: DotaRestDao;
constructor(dataService: DotaRestDao) {
this.result = { matches: [] };
this.dataService = dataService;
this.dataService.getData({
baseUrl: DotaRestDao.MATCH_HISTORY_BASE
}).subscribe(
res => this.result = res.result,
err => console.log("something wrongable", err),
() => console.log('completed')
);
}
}
//模板
<table class="table">
...
<button (click)="setPath(match.match_id)">Match Detail Route</button>
</table>
1 回答
在这个问题的上下文中,即调用父亲
router
,结果证明答案是微不足道的 . 有关详细信息,请参阅this plunker .主要内容是将路由器提供给子组件1a
不创建新路由器,它只是扩展父组件的现有路由器 . 因此,避免了对父对象的引用的需要 . 只需调用childRouter的方法,一切都按预期工作 .