在 Angular 4 中显示订阅数据

Display Subscribe Data in Angular 4

我需要帮助来显示 Angular 中 api 的订阅输出 4。自从我写了 data.data.data 但它说 属性 我该怎么做类型对象上不存在数据。我将如何在浏览器中输出它?下面是我的代码和下面的 api 图片

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';

@Component({
  selector: 'app-news-list',
  templateUrl: './news-list.component.html',
  styleUrls: ['./news-list.component.css']
})
export class NewsListComponent implements OnInit {

  constructor(private newsService: NewsService) { }

  ngOnInit() {

    this.newsService.getNews()
      .subscribe(
        data => {
          alert("News Success");
          console.log(data);
        },
        error => {
          alert("ERROR");
        });
  }
}

你的数据是数组类型,

创建任意类型的变量

myData : any;

并将数据分配给 myData,

this.newsService
    .getNews()
    .subscribe(
        data => {
           this.myData = data.data;
        },
        error => {
          alert("ERROR");
        }
    );

你可以使用ngFor遍历数组并显示在HTML

<li *ngFor="let item of myData">
     {{item}}
</li>

在组件

中创建一个属性
myData: any[] = [];

并在您的订阅者功能中

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';

@Component({
  selector: 'app-news-list',
  templateUrl: './news-list.component.html',
  styleUrls: ['./news-list.component.css']
})
export class NewsListComponent implements OnInit {

  constructor(private newsService: NewsService) { }

  ngOnInit() {

    this.newsService.getNews()
      .subscribe(
        (res: any) => {
          alert("News Success");
          this.myData = res.data; 
          // Where you find the array res.data or res.data.data
          console.log('res is ', res.data);
        },
        error => {
          alert("ERROR");
        });
      }
    }

并在您的模板中

1) 查看选项 JSON

<pre>{{myData | json}}</pre>

2) 如果你得到数组

循环选项
<div *ngFor="let d of myData">
    {{d}}
</div>

你需要这样做

ngOnInit() {
 this.newsService.getNews()
  .subscribe(
    data => {
      data = data.json();
      console.log(data.data);
    },
    error => {
      alert("ERROR");
    });

}

data.json() 部分很重要,它将响应转换为正确的 json 以便可以访问其数据。 现在你可以像这样将它分配给实例变量

this.myArrayData = data.data

在您的 subscribe() 方法中 然后在你的模板中

<div *ngFor="let data of myArrayData">
  <!-- do whatever with the data properties -->
</div>