在Angular 4中显示订阅数据 [英] Display Subscribe Data in Angular 4

查看:341
本文介绍了在Angular 4中显示订阅数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help in displaying the output of subscribe from an api in Angular 4. How can i do this since I wrote data.data.data but it says property data doesnt exist on type object. How would i output it in the browser? Here's my code below and the api picture below

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[] = [];

以及您的订户功能中

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

1) option to view JSON

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

2)如果有数组则循环播放

2) option to loop if you got the array

<div *ngFor="let d of myData">
    {{d}}
</div>

这篇关于在Angular 4中显示订阅数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆