When I use angular 9 ngFor, the array does not show the corresponding data

211 views Asked by At

I am new to using angular. When creating a blog project, I need to show all the tags of the article; when I use ngFor, it has no effect. I hope everyone can help me to see if there is something wrong with what I wrote.

package.json

{
  "dependencies": {
    "@angular/animations": "~9.0.3",
    "@angular/common": "~9.0.3",
    "@angular/compiler": "~9.0.3",
    "@angular/core": "~9.0.3",
    "@angular/forms": "~9.0.3",
    "@angular/platform-browser": "~9.0.3",
    "@angular/platform-browser-dynamic": "~9.0.3",
    "@angular/router": "~9.0.3",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  }
}

article-list.component.ts

import { Component, OnInit } from '@angular/core';
import { ConfigService } from 'src/app/@core/service/config';

@Component({
  templateUrl: './article-list.component.html',
  styleUrls: ['./article-list.component.scss']
})
export class ArticleListComponent implements OnInit {
  title = 'blog-articles';
  public tags: { text }[] = [ { text: '11'} ];

  constructor(
    private configService: ConfigService
  ) {}

  ngOnInit() {
    this.configService.getTags().subscribe(
      data => {
        this.tags = data.data;
        console.log(this.tags);
      }
    );
  }
}

article-list.component.html

    ---<br />
    <div *ngFor="let tag of tags">
        {{ tag.text }}
    </div>
    ---<br />

    {{tags[0].text}}

tags json:

0: {_id: "5e5b626acc959bf39e9e257f", text: "JavaScript", value: "JavaScript"}
1: {_id: "5e5b6284cc959bf39e9e259e", text: "Css", value: "Css"}
2: {_id: "5e5b629dcc959bf39e9e25ac", text: "Mac", value: "Mac"}
3: {_id: "5e5caed8cc959bf39e9ea0dd", text: "Redis", value: "Redis"}
1

There are 1 answers

7
Emilien On BEST ANSWER

What if you change you code like this :

public tags: { text: string }[] = [ { text: '11'} ];

ngOnInit() {
  this.configService.getTags().subscribe(({ data }) => {
    this.tags = data;
    console.log(this.tags);
  });
}

I've made a quick Stackblitz. Please pay attention to the tags.json format.