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