Display Subscribe Data in Angular 4

烈酒焚心 提交于 2019-12-03 20:28:13

create a property in component

myData: any[] = [];

and in your subscriber function

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

and in your template

1) option to view JSON

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

2) option to loop if you got the array

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

Your data is type of array,

Create a variable of type any

myData : any;

and assign the data to myData,

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

you can use ngFor to iterate over array and display in the HTML

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

You need to do it like this

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

}

the data.json() part is important, it converts the response into proper json so can access its data. Now you can assign it to instance variable like this

this.myArrayData = data.data

inside your subscribe() method Then in your template

<div *ngFor="let data of myArrayData">
  <!-- do whatever with the data properties -->
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!