首页 > 解决方案 > 当我使用 angular 9 ngFor 时,数组不显示相应的数据

问题描述

我是使用角度的新手。创建博客项目时,需要显示文章的所有标签;当我使用 ngFor 时,它没有任何效果。希望大家帮我看看我写的有没有问题。

包.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);
      }
    );
  }
}

文章列表.component.html

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

    {{tags[0].text}}

标签 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"}

标签: node.jsangularmongodb

解决方案


如果您像这样更改代码怎么办:

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

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

我做了一个快速的Stackblitz。请注意tags.json格式。


推荐阅读