2017-02-17 41 views
1

我正在通過構建一個小博客來學習angular2。 我使用打字稿2的角度cli。Angular2 [routerLink]構建失敗

我有一個小組件的問題。 當您在文章頁面中時,我需要一個「上一步」和「下一步」鏈接來訪問其他文章。

我的路徑是由這樣的:文章/:ID /:塞

在我的類組件:到目前爲止我的代碼(和我的問題,下面):

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() 
    ); 
} 

我得到了我的d ATAS,服務工作正常但是...

我的問題:

當我打電話給我的this.getUrlParams()在ngOnInit()法,[routerLink]在我的模板中顯示一個錯誤。該對象未找到。

[routerLink]="['/article', nextArticle.id, nextArticle.slug] 

但是,當我將我的方法移入類構造函數時,它的工作原理。我知道這不是一個很好的做法,我寧願將所有內容都移動到ngOnInit()

任何想法如何做到這一點?我有點現在輸了...

SOLUTION:

添加HTML元素:

*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]" 

它會等待數據呈現前:)謝謝岡特

回答

1

您可以添加一個*ngIf以防止在nextArticle可用之前創建routerLink

*ngIf="nextArticle" [routerLink]="['/article', nextArticle.id, nextArticle.slug]" 

[routerLink]="nextArticle ? ['/article', nextArticle.id, nextArticle.slug] : null" 
+0

感謝您的回答!我已經嘗試過了,但是頁面上沒有顯示任何內容...... – KCarnaille

+0

不確定你的意思是什麼「無」。只有具有routerLink的元素纔會顯示,並且只有'nextArticle'尚不可用。我會用另一種方法更新我的答案。 –

+1

好吧,對不起,我的回答太快了。出於任何原因,您的解決方案實際上可行我昨天試過了,並沒有工作......我認爲這是一個錯誤的LOL。再次感謝 ! – KCarnaille