I am facing an issue with my code where the Get
request is unable to fetch api values for posts, although it was successful for users. The code is simple, but I can't seem to figure out why it fails for posts.
Here is my posts.components.ts file:
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');
}
}
Upon checking the console, it shows undefined and on the html page only the header is visible without any data. What steps should I take to resolve this issue?