Angular – Github

We are building Github profile finder, in our app, we have a search bar and based on the name we supply. App will search following information on that particular user

  1. User profile information and avatar
  2. Follower info
  3. Github repository info

Important: As  from Angular point, we are learning ngIf to control the display, at first we set user to false, as this result our page is blank with only search bar and once we type any character it will set user to that character and find information on that user , as we can see on image above.

What we are learning

  1. Retrieving Github API through HTTP get method .
  2. Making service provider
  3. Importing form module for searching information through form

 

Step 1: Getting Github Client Id
To use the Github API, we need to get a client id and client secret, that we will get from github.com/settgins/developer and register for a new application.

Step 2: Setting the App in Angular
ng new githubse
npm install (install the dependency)
npm start
Check on browser on url localhost:4200

Step 3: Creating Profile component

Create a folder components inside the app folder and add new two new files as profile.component.ts and profile.component.html. Inside the profile.component.ts add the following code [app/components/profile.component.ts]

import { Component } from '@angular/core';
import {GithubService} from '../services/github.service';

@Component({
  moduleId: module.id,
  selector: 'profile',
  templateUrl: 'profile.component.html',
})

export class ProfileComponent { 
    user:any;
    repos:any[];
    username: string;
    
    constructor(private _githubService: GithubService){
        this.user = false;
    }

    searchUser(){
        this._githubService.updateUser(this.username);

        this._githubService.getUser().subscribe(user => {
            this.user = user;
        });

        this._githubService.getRepos().subscribe( repos => {
            this.repos = repos;
        });

    }
}

We are importing the GithubService service provider and calling its method through the instance of GithubService and subscribing the observable which we will define in step 5. What we are doing.

  1. Calling Github user information through GithubService method getUser()
  2. Retrieving user repository through getRepos()
  3. Search different user through updating or change new username through updateUser() of GithubService

Step 4: Add the view for profile.component.html, add the following code in [app/components/profile.component.html]. In this code, we add a search bar to retrieve Github user information like profile, avatar, followers and repository details information.

<div class="row">
    <div class="col-md-12">
        <form class="well"> 
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Enter Github Username .." [(ngModel)]="username" name="username" (keyup)="searchUser()">
            </div>
        </form>
    </div>    
</div> <!-- End of row -->

<div *ngIf="user">
   <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">{{user.name}}</h3>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-4">
                    <img class="img-thumbnail" src="{{user.avatar_url}}">
                    <a class="btn btn-default btn-block" target="_blank" href="{{user.html_url}}">View Profile</a>
                </div>
                <div class="col-md-8">
                    <div class="stats">
                        <span class="label label-default">{{user.public_repos}} Public Repos</span>
                        <span class="label label-primary">{{user.public_gists}} Public Gists</span>
                        <span class="label label-success">{{user.followers}} Followers</span>
                        <span class="label label-info">{{user.following}} Following</span>
                    </div>
                    <br>
                    <ul class="list-group">
                        <li class="list-group-item"><strong>Username: </strong>{{user.login}}</li>
                        <li class="list-group-item"><strong>Location: </strong>{{user.location}}</li> 
                        <li class="list-group-item"><strong>Email: </strong>{{user.email}}</li> 
                        <li class="list-group-item"><strong>Blog: </strong>{{user.blog}}</li> 
                        <li class="list-group-item"><strong>Member Since: </strong>{{user.created_at}}</li> 
                    </ul>
                </div>    
            </div>
        </div>
    </div>
    
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">User Repos</h3>
        </div>
        <div class="panel-body">
            <div *ngFor="let repo of repos">
                  <div class="row">
                    <div class="col-md-9">
                        <h4><a target="_blank" href="{{repo.html_url}}">{{repo.name}}</a></h4>
                        <p>{{repo.description}}</p>
                    </div>
                    <div class="col-md-3">
                        <span class="label label-default">{{repo.watchers}} Watchers</span>
                        <span class="label label-primary">{{repo.forks}} Forks</span>
                    </div>  
                  </div>
                  <hr>
            </div>
        </div>
    </div>
</div>

 

In app/app.component.ts we will replace following code

@Component({
	.......
	template: '<h1>My First Angular App</h1>
})

To new code, where we add our custom tag profile and wrap in container div and add nav bar code from bootstrap starter code and add the provider as in highlight in the code

import { Component } from '@angular/core';
import { GithubService } from './services/github.service';

@Component({
  selector: 'app-root',
  template: `
     <nav class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Github Search</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
           
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>
    <div class="container">
        <profile></profile>
    </div>`,
        
  styleUrls: ['./app.component.css'],
  providers: [ GithubService ]
})
export class AppComponent {
  title = 'app';
}

 

Step 5: Creating  Service for Github API
We will create Github services so that it can interact with Github API. In the app, folder creates a folder called services, inside this folder add a new file called app/services/github.service.ts. Add the following code

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

@Injectable()
export class GithubService{
    private username:string;
    private client_id ='386c70968833e0b2c';
    private client_secret = '4af330c6ca939274cee0a5221a8469edd3e';

    constructor(private _http: Http){
        console.log('Github Service Ready...');
        this.username = 'n????p';
    }

    getUser(){
        return this._http
        .get('http://api.github.com/users/' + this.username + '?client_id=' + this.client_id + '&client_secret=' + this.client_secret)
            .map(res => res.json());
    }

    getRepos(){
        return this._http
        .get('http://api.github.com/users/' + this.username + '/repos?client_id=' + this.client_id + '&client_secret=' + this.client_secret)
            .map(res => res.json());
    }

    updateUser(username:string){
        this.username = username;
    }
}

In above code,

  1. we are retrieving user information in JSON format through HTTP module and we have to supply client ID and secret key.
  2. Import injectable so we can create dependency on service into whatever component we need.
  3. Import rxjs, observable with the reactive extension will return the response to observable, then we can subscribe to the observable component to display the information.

Step 6: Define user interface through Bootstrap
Add the following link in src/index.html, this is not best practices.

<!doctype html>
<html lang="en">
<head>
.........

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 

In app.modules.ts, we have to define imported module, the custom component which we had used in our application.

import { HttpModule } from '@angular/http';
import { FormsModule} from '@angular/forms';

import { ProfileComponent } from './components/profile.component';

@NgModule({
  declarations: [ AppComponent, ProfileComponent],
  imports: [ BrowserModule, HttpModule, FormsModule ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }