2017-02-15 56 views
0

我嘗試顯示一個數組,我從mongodb中獲取(Chrome網絡工具顯示我得到它(與文章響應))。我沒有得到任何錯誤,但文章沒有顯示在模板中。Angular 2從GET請求顯示數組無法顯示

這裏是模板:

<div class="container-fluid"> 
    <div class="row"> 
     <div *ngIf="articles"> 
     <div class="col-lg-5 sm-12 m-6" *ngFor="let arts of articles"> 
     <div class="list-group "> 
       <!--TODO: Link to ViewArticle--> 
      <a href="#" class="list-group-item list-group-item-action felx-column 
       align-items-start active"> 
       <div class="d-flex w-100 justify-content-between"> 
        <h5 class="mb-1">{{arts.headline}}</h5> 
        <small>{{arts.updated_at}}</small> 
        </div> 
        <p class="mb-1">{{arts.textarea}}</p> 
    <small class="text-muted mutedText"> 
        MutedText.MutedText.MutedText.</small> 
        </a> 
      </div> 
      </div> 
     </div> 
    </div> 
</div> 

的getArticles()在組件方法:文章數組聲明!

getArticles():Promise<Article[]>{ 
     return this.articleService.getArticles() 
          .then(articles => this.articles = articles); 
    } 

以及服務的getArticles()方法:

getArticles(): Promise<Article[]>{ 

     return this.http.get(`${BASE_URI}${PATH_ARTICLES}`) 
        .toPromise() 
        .then((r: Response) => r.json().data as Article[]) 
        .catch(this.handleError); 

    } 

在此先感謝, 我不能在網絡上找到任何東西..

+0

你可以看到你''然後在()的組件內部的相關數據?你可以把'console.log()'分配給'this.articles'之前嗎? – echonax

+0

此外,另一個簡單的測試,看看該任務是否按預期工作:只要把

{{articles}}

某處(當然不是在* ngIf裏面) – dquijada

+0

確定後我添加了console.log() '到.then()'文章顯示在視圖..如何可以? – Vale

回答

1

我曾問過類似的問題,這樣的:custom created method error: "is not a function"從GünterZöchbauer回答:

「如果您將JSON投射到TypeScript類,一切正在發生的是,你向靜態分析指出它可以安全地假定該類的價值,它實際上並沒有改變JSON值,也沒有使它成爲該類的一個實例。「

你的問題在這裏:.then((r: Response) => r.json().data as Article[])。你將它們聲明爲Article的數組,但它們不是。它會起作用,但實際上它們是(如果我錯了,請糾正我,這對我來說也是一個新話題)簡單的對象。

您可以將對象添加到Article數組,但並不意味着添加的對象變成一個Article

+0

我從Angular的英雄之旅中複製了'.then()'塊,但我會接受 – Vale