在Angular 4中显示订阅数据

时间:2017-09-07 04:25:56

标签: json angular angular-http angular-httpclient

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

enter image description here

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

3 个答案:

答案 0 :(得分:9)

在组件中创建属性

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>

答案 1 :(得分:1)

您的数据是数组类型,

创建任何类型

的变量
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>

答案 2 :(得分:1)

你需要这样做

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>