The code I am using is nothing too complicated but I cannot seem to figure out why the Get request is unable to fetch the api values. It was able to do so with the users but when it comes to the posts it fails miserably.
This is my posts.components.ts :-
import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import {Observable} from 'rxjs';
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
posts$: Object;
constructor(private pdata: DataService) {
}
ngOnInit() {
this.pdata.getPosts().subscribe(
pdata => this.posts$ = pdata
)
console.log(this.posts$);
}
}
This is the html file :-
<h1>Posts</h1>
<ul>
<li *ngFor = "let pst of post$">
<a routerLink=""> {{post$.title}}</a>
<p>{{post$.body}}</p>
</li>
</ul>
And this is my service file
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers(){
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
getUser(userid){
return this.http.get('https://jsonplaceholder.typicode.com/users/'+userid)
}
getPosts(){
return this.http.get('https://jsonplaceholder.typicode.com/posts');
}
}
On checking the console, it says undefined and in the html page only the header is visible and no data. What do I do?
posts$should bepostsin your component (it's not an observable). It's supposed to be an array, not an object, so don't type it as Object. In the template,post$should beposts.pstshould bepost.post$.titleshould bepost.titleSame for body.