I have tried to fetch user api data from github, by angular 2 http, it works because response is like { }. But when I try to fetch data for repositories of the same user it returns a response like [{},{},{},]. I can handle that response in simple JavaScript but via angular 2 http get it returns response successfully but shows [object Object],[object Object] in console if I try to console.log it. But when I try to access inner properties like respone[0].name it says undefined. Here is the code:
import { Component, OnInit } from '@angular/core';
import { GithubProfile,RepoProfile } from '../github-profile';
import { GitHubAPIService } from '../git-hub-api.service';
@Component({
selector: 'app-github-profile',
template: `
<div class="row">
<div class="col-md-12 alert alert-info" [hidden]="!charging">Charging..</div>
<div class="col-md-4">
<form name="form" class="form" (ngSubmit)="findProfile()" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input id="username" type="text" class="form-control" [(ngModel)]="username" name="username" #user="ngModel" required>
<div [hidden]="user.valid" class="alert alert-danger">This field can't be blank</div>
</div>
<button class="btn btn-success" type="submit" [disabled]="user.invalid">Find</button>
</form>
</div>
<div class="col-md-8 text-center">
<div class="row">
<div class="col-sm-6 col-md-4" *ngIf="auxProfile">
<div class="thumbnail">
<img src="{{auxProfile.avatar_url}}" alt="user_avatar">
<div class="caption">
<h3>{{auxProfile.name}}</h3>
<p>{{auxProfile.login}}</p>
<p>{{auxProfile.location}}</p>
<a href="{{auxProfile.repos_url}}" (click)="findRepo(auxProfile.repos_url )" class="btn btn-primary" role="button">Show Repositories</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12 col-md-12" *ngIf="repoProfile">
<div *ngFor= "let repo of repoProfile; let i = index;">
<a href="{{repo[i].contributors_url}}" class="btn btn-danger">{{repo[i].name}}</a>
</div>
</div>
</div>
`,
providers: [GitHubAPIService]
})
export class GithubProfileComponent implements OnInit {
auxProfile: GithubProfile = null;
repoProfile: RepoProfile;
errorMessage: string;
username = 'angular';
repoUrl= '';
charging: boolean;
constructor(private gitHubAPIService: GitHubAPIService) {
this.charging = false;
}
ngOnInit() {
}
findProfile(){
this.charging = true;
this.gitHubAPIService.getProfile(this.username)
.subscribe(profile => {this.auxProfile = profile; this.charging = false},
error => {this.errorMessage = error; this.charging = false;});
}
findRepo(repoUrl) {
this.gitHubAPIService.getRepo(repoUrl)
.subscribe(
response => { this.repoProfile = response;console.log("Success Response" + this.repoProfile);},
error => { console.log("Error happened" + error)},
() => { console.log("the subscription is completed")}
);
}
}
And the services for the same component where getRepo() method is actually called is having this code:
import { Injectable } from '@angular/core';
import { GithubProfile,RepoProfile} from './github-profile';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class GitHubAPIService {
constructor (private http: Http) {}
private GITHUB_API_URL = 'https://api.github.com/users/';
getProfile(username:string) : Observable<GithubProfile>{
return this.http.get(`${this.GITHUB_API_URL}${username}`)
.map(this.extractData)
.catch(this.handleError);
}
getRepo(repoUrl:string) : Observable<RepoProfile>{
return this.http.get(`${repoUrl}`)
.map(response => response.json())
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
and I have one more code for RepoProfile, it used to decide that this kind of object will be returned it is used in getRepo():Observable{}
export class GithubProfile {
name: string;
location: string;
avatarUrl: string;
//username
login: string
constructor(login: string, name: string, location: string, avatarUrl: string) {
this.name = name;
this.login = login;
this.avatarUrl = avatarUrl;
this.location = location;
}
}
export class RepoProfile {
name: string;
contributors_url: string;
constructor( name: string, contributors_url: string) {
this.name = name;
this.contributors_url = contributors_url;
}
}