【发布时间】:2017-07-07 04:51:08
【问题描述】:
我正在通过建立一个小博客来学习 angular2。 我将 angular-cli 与 typescript 2 一起使用。
我遇到了一个小组件的问题。 当您在文章页面中时,我想要一个“上一个”和“下一个”链接来访问其他文章。
我的路径是这样的:article/:id/:slug
在我的类组件中:到目前为止我的代码(以及我的问题,如下):
getUrlParams() {
this.activatedRoute.params.subscribe( (param) => {
this.loadPrevArticle(param);
})
}
loadPrevArticle(param){
let id = Number(param['id']); // Converts the original string to number
return this.myService.getArticles().subscribe((data) => {
// some stuffs to get the article object I want, actually working :)
});
}
我的服务如下所示:
getArticles() {
return this.http.get('my_api_link').map(
(res: Response) => res.json()
);
}
我得到了我的数据,服务运行正常但是......
我的问题:
当我在 ngOnInit() 中调用 this.getUrlParams() 方法时,模板中的 [routerLink] 显示错误.找不到对象。
[routerLink]="['/article', nextArticle.id, nextArticle.slug]
但是当我将我的方法移动到类构造函数中时,它就可以工作了。我知道这样做不是一个好习惯,我宁愿移动 ngOnInit() 中的所有内容
任何想法如何做到这一点?我现在有点迷茫……
解决方案:
在html元素上添加:
*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"
它会在渲染前等待数据 :) 谢谢 Gunter
【问题讨论】:
标签: javascript angular typescript2.0