0

I try to display an array which I fetch from mongodb (Chrome networktool shows that I get it (response with articles)). I dont get any error but the articles arent shown in the template.

Here is the template:

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

The getArticles() method in the Component: the articles array is declared!

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

And the service's getArticles() method:

 getArticles(): Promise<Article[]>{

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

    }

Thanks in advance, I cant find anything on the net..

Valentin
  • 108
  • 7
  • Can you see the relevant data inside your `then()` in your component? Can you put a `console.log()` before you assign it to `this.articles`? – eko Feb 15 '17 at 13:00
  • Also, another easy test to see if the assignment is working as intended: just put a

    {{articles}}

    somewhere (not inside of the *ngIf, of course)
    – dquijada Feb 15 '17 at 13:03
  • ok after I added the `console.log()` to the `.then()` the articles are shown in the view..how could that be ? – Valentin Feb 15 '17 at 13:19

1 Answers1

1

I once asked a similar question to this: custom created method error: "is not a function" with an answer from 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."

Your problem is here: .then((r: Response) => r.json().data as Article[]). You declared them as array of Article but they aren't. It'll work but in reality they are (correct me if I'm wrong. It's a new topic for me too) simple objects.

You can add objects to an array of Article but that doesn't mean the added objects turns into an Article

Community
  • 1
  • 1
SuffPanda
  • 348
  • 2
  • 17