Angular 2 无法显示来自 GET 请求的数组

Angular 2 Cant display Array from GET-Request

我尝试显示我从 mongodb 获取的数组(Chrome networktool 显示我得到它(对文章的响应))。我没有收到任何错误,但模板中没有显示文章。

这是模板:

<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>

Component中的getArticles()方法:声明了articles数组!

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

    }

提前致谢, 我在网上找不到任何东西..

我曾经问过一个类似的问题: Günter Zöchbauer 的回答是:

"If you cast JSON to a TypeScript class, all is happening is that you indicat to the static analysis it can safely assume the value being of that class, that doesn't actually change the JSON value at all and also doesn't make it an instance of that class."

您的问题在这里:.then((r: Response) => r.json().data as Article[])。您将它们声明为 Article 的数组,但它们不是。它会起作用,但实际上它们是(如果我错了请纠正我。这对我来说也是一个新话题)简单的对象。

您可以将对象添加到 Article 的数组中,但这并不意味着添加的对象会变成 Article