0

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?

10
  • 1
    You have plenty of errors everywhere. posts$ should be postsin 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 be posts. pst should be post. post$.titleshould be post.title Same for body. Commented Jul 10, 2018 at 6:28
  • @JBNizet fyi I am referring from here since I am still learning Angular 6. Hold on, I will let you know the results. If you can check the link, you can see the same thing has been done in the users component and user view is working fine Commented Jul 10, 2018 at 6:30
  • Err, yes. You're asking why your code doesn't work, and I'm telling you why. What's the problem? Commented Jul 10, 2018 at 6:30
  • @JBNizet I did make the necessary changes but still nothing. Rather it was actually showing undefined before in the console and now it is showing nothing\ Commented Jul 10, 2018 at 6:33
  • Your console.log, as the response from Sajeetharan tells you, doesn't make sense. You can't expect to read the response to an email immediately after sending the email. You can only read the response when the receiver has responded. Same here. Commented Jul 10, 2018 at 6:35

5 Answers 5

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry but this method gave me even more "undefined" errors. I appreciate the help but it just made it worse. I am aware of the typos though. I had not noticed the post in the *ngFor had become pst but the main problem lay in the line pdata => this.posts$ = pdata Since the same data variable is being used everywhere, I mistook it for a local variable and when I tried to name each variable differently, I was met with this error
0

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>

1 Comment

When i do that it says Argument of type 'void' is not assignable to parameter of type '(error : any) => void'
0

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

2 Comments

It does matter, because the $ suffix is a convention to say that the variable is an Observable, whereas posts$ is not an observable. So you're confusing the poor guy who has to maintain your code by doing that. Just like if you named firstName a variable holding the lastName and vice-versa. The compiler doesn't care, but the maintainer does. Your second part doesn't make any sense: you can choose the name you want for your local variables and arguments. Bu yes, data is less confusing, since you also have an instance variable named pData (which is very badly named).
Not really. I just tested it out and indeed it was the second part of the code which I specifically mentioned. And yes it was a mistake on my part to include the $ suffix as I mentioned before, I am just learning this framework so I am not yet fully versed with all the sytnax rules. But thank you for the explanation but really, the pdata was the problem here.
0

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.