Angular2 [routerLink] 构建失败
Angular2 [routerLink] construction fail
我正在通过创建一个小博客来学习 angular2。
我使用 angular-cli 和 typescript 2.
我的一个小组件有问题。
当您在文章页面中时,我想要一个 "Previous" 和 "Next" 链接来访问其他文章。
我的路径是这样的:article/:id/:slug
在我的 class 组件中:到目前为止我的代码(和 我的问题,下面 ):
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]
但是当我将我的方法移动到 class 构造函数中时,它起作用了。我知道这不是一个好的做法,我更愿意移动 ngOnInit()
中的所有内容
有什么办法吗?我现在有点迷路...
解决方案:
添加 html 元素:
*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"
它会在渲染前等待数据 :) 谢谢 Gunter
您可以添加 *ngIf
以防止在 nextArticle
可用之前创建 routerLink
:
*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"
或
[routerLink]="nextArticle ? ['/article', nextArticle.id, nextArticle.slug] : null"
我正在通过创建一个小博客来学习 angular2。 我使用 angular-cli 和 typescript 2.
我的一个小组件有问题。 当您在文章页面中时,我想要一个 "Previous" 和 "Next" 链接来访问其他文章。
我的路径是这样的:article/:id/:slug
在我的 class 组件中:到目前为止我的代码(和 我的问题,下面 ):
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]
但是当我将我的方法移动到 class 构造函数中时,它起作用了。我知道这不是一个好的做法,我更愿意移动 ngOnInit()
中的所有内容有什么办法吗?我现在有点迷路...
解决方案:
添加 html 元素:
*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"
它会在渲染前等待数据 :) 谢谢 Gunter
您可以添加 *ngIf
以防止在 nextArticle
可用之前创建 routerLink
:
*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]"
或
[routerLink]="nextArticle ? ['/article', nextArticle.id, nextArticle.slug] : null"