pranavyoyo
pranavyoyo

Reputation: 85

Fetch the data from GITHUB API

I want to get all the data from github API. But it doesn't work for me. My .ts file is below:

import { Component } from '@angular/core';
import { GitTakeService } from "app/git-take.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user:any;

constructor(private gittakeService:GitTakeService ){

  this.gittakeService.getUser().subscribe(user=>{
    debugger;
    this.user=user;
    console.log(user);
  })

}
}

My service is below:

import { Injectable } from '@angular/core';
import {Http,Response, Headers} from '@angular/http'
import'rxjs/add/operator/map';

@Injectable()
export class GitTakeService {

  constructor(private http:Http) { }


  getUser(){
    debugger;
    return this.http.get("http://api.github.com/users")
        .map(
          (resp:Response)=>{

           return resp.json().response;
          }
        );    
  }    
}

When consoling the user in .ts file, it shows undefined. My view file is like this:

{{user}}

Anyone please help me to solve this problem?

Upvotes: 1

Views: 868

Answers (2)

AVJT82
AVJT82

Reputation: 73337

What you are receiving is an array, so you want to use resp.json() instead of resp.json().response there is no such property like response in your response. So your map should look like this:

getUser(){
  debugger;
  return this.http.get("http://api.github.com/users")
    .map((resp:Response)=>{
       return resp.json();
    });    
}

and in your component I would name the array users instead of user, since there are several users in your response. Also I suggest you keep anything unnecessary from the constructor and use OnInit instead:

users = [];

constructor(private gittakeService:GitTakeService ){ }

ngOnInit() {
  this.gittakeService.getUser()
    .subscribe(data => {
       this.users = data;
    });
}

Then you can iterate the array and use the property names to show the properties of one user object:

<div *ngFor="let user of users">
  {{user.login}}
</div>

Upvotes: 1

Yonatan Lilling
Yonatan Lilling

Reputation: 298

resp.json().response is undefined resp.json() is what you want

the service function:

getUser(){
   return this.http.get("http://api.github.com/users")
    .map(
      (resp:Response)=>{

       return resp.json();
      }
    );

}`

and the component:

this.gittakeService.getUser().subscribe(users=>{
    this.user=users[0];
    console.log(user);
})

Upvotes: 0

Related Questions