R.D
R.D

Reputation: 226

Unable to fetch api values in angular 6

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?

Upvotes: 0

Views: 2140

Answers (5)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24404

Just fix this posts$ should be array of any

 posts$: any[];

And it is safe to initialize with empty array like this

 posts$: any[] =[];

In order to check the result(pdata) value just move console.log to subscribe callback or just check the network panel in chrome developer tool :

ngOnInit() {
      this.pdata.getPosts().subscribe(pdata => {
           this.posts$ = pdata;
           console.log(this.posts$);
  });  
}

Upvotes: 0

Ali Rida
Ali Rida

Reputation: 381

Your html file should be like this:

<h1>Posts</h1>
<ul>
  <li *ngFor = "let post of posts$">
    <a routerLink=""> {{post.title}}</a>
    <p>{{post.body}}</p>
  </li>
</ul>

Also you have to put the console.log inside your api call funnction like this:

ngOnInit() {
    this.pdata.getPosts().subscribe(
      pdata => { 
          this.posts$ = pdata;
          console.log(this.posts$);
      }
    )  
}

It may not be the main issue but it may help figuring out the main problem, please try it out and keep me updated so we can solve it!

Upvotes: 0

R.D
R.D

Reputation: 226

I really do appreciate all of you who have answered and tried to help me but I have solved the problem. It did not matter if posts was posts$ as I am using it as just a variable name.

The problem was here

 ngOnInit() {
      this.pdata.getPosts().subscribe(
        pdata => this.posts$ = pdata

Instead of pdata => this.posts$ = pdata It should have been data => this.posts$ = data as it is being called from the DataService module I have called. So by changing it to pdata, it was not able to identify the module hence I was unable to see any data in the html file. It's working now

Upvotes: 0

Bhanu Tej P
Bhanu Tej P

Reputation: 230

First you are logging outside subscribe. That means before data is fetched from api your are logging it. Change it as below

  ngOnInit() {
   this.pdata.getPosts().subscribe(
     pdata => {
       this.posts$ = pdata
       console.log(this.posts$);
     } 
   )
  }

Now in your html you are using post$ but you have declared posts$ in ts and there are some other typos in your code. So change it to

<h1>Posts</h1>
<ul *ngIf="posts$.length > 0">
  <li  *ngFor = "let post of posts$">
   <a routerLink=""> {{post.title}}</a>
   <p>{{post.body}}</p>
  </li>
</ul>

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222532

You should place the console.log only inside subscribe,

 ngOnInit() {
      this.pdata.getPosts().subscribe(
        pdata => {
          this.posts$ = pdata;
          console.log(this.posts$);
        });    
  }

and if you to access the variable in the component use *ngIf or safe navigation operator since your request is asynchronous

 <a routerLink=""> {{post$?.title}}</a>
    <p>{{post$?.body}}</p>

Upvotes: 0

Related Questions