create account

Consuming GitHub API using Angular JS by chri5h

View this thread on: hive.blogpeakd.comecency.com
· @chri5h · (edited)
$59.31
Consuming GitHub API using Angular JS
# <center>Consuming GitHub API using Angular JS</center>

#### Repository: https://github.com/angular/angular.js

#### What will I Learn?

In this tutorial, you will learn the following

- Consume the github web service and get required data
- Search for github users using a search form
- Display results based on search input
- Sort the search result of user repository
- Use angular filters to format the result
- Display a custom error message when data loading fails

#### Requirements

For this tutorial, you will need the following

- A laptop with any operating system such as Windows OS, Mac OSX and Linux
- Your favorite text editor 
- Internet access
- Knowledge of HTML, JavaScript
- Download the <a href="https://angularjs.org">ANGULAR JS</a> script or include the cdn link <https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js>

#### Difficulty

- Basic

#### Tutorial Content

Angular JS framework which started from google and now an open source project such that anyone is allowed to use it or contribute to the project. Working with angular JS gives you more flexibility and power while implementing your project. This tutorial allows us to use angular js to consume the <a href="https://api.github.com/users/angular">github api</a> available to us to get various details of a github user. In the course of the tutorial, we will be able to retrieve data from the api using a search form, display the information on our webpage and as well sort the user repository as we wish.

#### Step 1: Getting Started

To begin this course you will need to include the angular js script to the index.html file either using the cdn link or the angular.min.js file downloaded from <a href="https://angularjs.org">Angular JS</a>. Then include a blank js script for writing our own angular js codes.

```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>GitHub Api using Angular JS</title>
    <script src="js/angular.min.js" charset="utf-8"></script>
    <script src="js/script.js" charset="utf-8"></script>
  </head>
  <body>
    <h1>GitHub viewer</h1>
  </body>
</html>
```

To confirm if your angular js was added successfully, you should not see any error on your browser console

#### Step 2: Get Angular Js up and running

Angular js requires you to provide a `ng-app` attribute in your HTML form which is an angular directive. The ng-app stands for angular which triggers the angular js to function within your HTML form.

```html
<!DOCTYPE html>
<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>GitHub Api using Angular JS</title>
    <script src="js/angular.min.js" charset="utf-8"></script>
    <script src="js/script.js" charset="utf-8"></script>
  </head>
  <body>
    <h1>GitHub viewer</h1>
  </body>
</html>
```

Then we could actually try out a mathematical expression to see that it functions properly by typing `{{ 453 / 3 }}` anywhere within the body tag.

NOTE: The ng-app directive can appear anywhere within the html form but it will only function within the area where the `ng-app` directive is located.

#### Step 3: Getting details of a single user through the API

We first have create a directive in our blank js script file which allows us create a controller which is in-charger of a particular area of our html file. To create a directive, you call the `angular.module()` and give it a name and an empty array for dependencies. The controller is then built based on the `app` directive that has been created earlier. We begin the controller with a controller name `MainCtrl`, a single dependency `$scope` and then a function with `$scope` as a the  only parameter.

```js
(function(){
  // create a directive
  var app = angular.module("myApp", []);
  
  // creates a controller called MainCtrl
  app.controller('MainCtrl', ['$scope', function($scope) {}]);

})();
```

To sent the request to the github api server, we require the angular `$http` depency to help send the request and return a response back to the script for further processing. Every `$http` request returns a result called a promise which we will use to create other required functions based on the response and also if there's an error while executing.

```js
// creates a controller called MainCtrl
  app.controller('MainCtrl', ['$scope','$http', function($scope, $http) {
// sends the request
  var promise = $http.get("https://api.github.com/users/chrix95");
  promise.then(onSuccess, onError);

  }]);
```

A request is sent to the github api and  stored to a variable `promise` which on success, execute the `onSuccess()` but if there is an error, executes the `onError()`.  This two functions currently do not exist, we will have to create it within the controller. The response gotten is attached to the dependency variable `$scope` based on the fact that the response is either a success or an error.

```js
var onSuccess = function(response){
    $scope.user = response.data; // this returns a json
}

var onError = function(response) {
    $scope.error = "Could not fetch data";
}
```

To preview changes, we need to attach our controller to the html within the ng-app directive  and display the result from our `$http` request. The request returns a JSON which we will select from view details to display such as the name of the user, location and image.

![singleUser.JPG](https://steemitimages.com/DQmNivEa8gpCwmWon1CTaTtnhVwq6dNACWhERrCi6vhtDmU/singleUser.JPG)

NOTE: 

- If angular was unable to retrieve the information, our custom error message displays on the screen.
- To see a list of the available detail that could be gottten, enter `https://api.github.com/users/? ` into your browser, where `?` stands for any github username.
- The ng-src directive of the image tag, allows angular to first process the url of the image before it is displayed on your browser.
- Check <a href="https://github.com/chrix95/github_api_angularjs/blob/master/singleUser.js">singleUser.js</a> and <a href="https://github.com/chrix95/github_api_angularjs/blob/master/singleUser.html">singleUser.html</a> for complete code snippet

#### Step 4: Create a form to search for GitHub users

The previous step allows us to get github users by changing the username in the `$http.get()` url. This step will show us how to get input from a form in our html and display the details of the user if it exist on github. To achieve this, we first create the form on our html and use the `ng-model` directive to pass the information from our html to the script for processing. The `ng-submit` directive sends the form details to the script once the submit button is click and then the `search()` in our JS script is executed to fetch the result.

```html
<form ng-submit="search(username)">
      <input type="search" ng-model="username">
      <input type="submit" value="Submit">
 </form>
```

In our script, the search function uses a parameter `username` which is collected from the form and it is attached to the the `$http.get` url in order to fetch the user details for display.

```js
$scope.search = function(username) {
	var promise = $http.get("https://api.github.com/users/" + username);
	promise.then(onSuccess, onError);
};
```

NOTE: 

- No changes needs to be made to the `onSuccess()` and `onError()`, the variable`promise` and `promise.then` is placed within the search $scope so it executes once the submit button is clicked on the form.
- Check <a href="https://github.com/chrix95/github_api_angularjs/blob/master/searchUser.js">searchUser.js</a> and <a href="https://github.com/chrix95/github_api_angularjs/blob/master/searchUser.html">searchUser.html</a> for complete code snippet

#### Step 5: Getting the repositories of searched GitHub user

Once we can finally use the search box to fetch user details, we can use the information to retrieve the user repository created on gihub with some features of the repository like stars, name, language and license of each repository. 

To achieve this, we modify the `onSuccess()` to use the details retrieved to send a `$http.get` request to fetch the repositories of that user then another function `onSearchResult()` - which we will create in our script file, is invoked on success of the `$http.get` request. `onSearchResult()` gets the response in JSON form and stores it to `$scope.repos` for access in the html file.

```js
$scope.search = function(username) {
    var promise = $http.get("https://api.github.com/users/" + username);
    promise.then(onSuccess, onError);
};

var onSuccess = function(response){
    $scope.user = response.data;
    var promise = $http.get($scope.user.repos_url);
    promise.then(onSearchResult, onError);
 }

var onSearchResult = function (response) {
	$scope.repos = response.data;
}

```

We need to modify our html file to view the changes effectively. We need to create a loop that goes through the data and populate our table.

```html
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Stars</th>
            <th>Language</th>
            <th>license</th>
        </tr>
    </thead>
<tbody>
    <tr ng-repeat="repo in repos">
        <td>{{repo.name}}</td>
        <td>{{repo.stargazers_count}}</td>
        <td>{{repo.language}}</td>
        <td>{{repo.license.name}}</td>
    </tr>
</tbody>
</table>
```

NOTE: 

- The `ng-repeat` is a directive in angular js that acts as a foreach loop to display the retrieved data into a given area. 
- The value `repo` holds each repository available in `repos`. Then each td carries the values of each repository attribute such as the name, stars (represented as stargazer_count), language of the repository and license name.
- To see a list of the available details or attributes that could be retrieved, enter `https://api.github.com/users/?/repos ` into your browser, where `?` stands for any github username.

#### STEP 6: Sort the search result of user repository

To achieve this, we create a select input on our html and use the `ng-model` directive to pass the information from our html to the script for processing. Once the value of the select box changes, it triggers the sorting of the repository table.

```html
<select ng-model="orderSortBy">
    <option value="+name">Name</option>
    <option value="-stargazers_count" selected>Stars</option>
    <option value="+language">Language</option>
    <option value="+license">License</option>
</select>

<tr ng-repeat="repo in repos | orderBy: orderSortBy">
```

NOTE: 

- The `+` in front of the values indicate Ascending order and the `-` indicates Descending order.
- we have to pass a filter `orderBy` through a "pipe" `|` into our `ng-repeat` with a variable name `orderSortBy` so that it changes the order once the select input changes value.

To make the sorting functional, we create a new `$scope` within our controller and give it a value which eventually changes as the select input changes.

```js
$scope.orderSortBy = "-stargazers_count";
```

- Check <a href="https://github.com/chrix95/github_api_angularjs/blob/master/sortRepo.js">sortRepo.js</a> and <a href="https://github.com/chrix95/github_api_angularjs/blob/master/sortRepo.html">sortRepo.html</a> for complete code snippet

#### Proof of Work Done

I hope you find this tutorial very useful and you can access the complete code for this tutorial in the <a href="https://github.com/chrix95/github_api_angularjs">github repo</a>.
👍  , , , , ,
properties (23)
authorchri5h
permlinkconsuming-github-api-using-angular-js
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","angularjs","steemjet","github"],"links":["https://github.com/angular/angular.js","https://angularjs.org","https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js","https://api.github.com/users/angular","https://github.com/chrix95/github_api_angularjs/blob/master/singleUser.js","https://github.com/chrix95/github_api_angularjs/blob/master/singleUser.html","https://github.com/chrix95/github_api_angularjs/blob/master/searchUser.js","https://github.com/chrix95/github_api_angularjs/blob/master/searchUser.html","https://github.com/chrix95/github_api_angularjs/blob/master/sortRepo.js","https://github.com/chrix95/github_api_angularjs/blob/master/sortRepo.html","https://github.com/chrix95/github_api_angularjs"],"app":"steemit/0.1","format":"markdown","image":["https://steemitimages.com/DQmNivEa8gpCwmWon1CTaTtnhVwq6dNACWhERrCi6vhtDmU/singleUser.JPG"]}
created2018-05-20 06:09:15
last_update2018-05-20 12:47:33
depth0
children5
last_payout2018-05-27 06:09:15
cashout_time1969-12-31 23:59:59
total_payout_value44.699 HBD
curator_payout_value14.606 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length11,380
author_reputation2,291,303,072,819
root_title"Consuming GitHub API using Angular JS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id56,658,430
net_rshares13,175,341,379,344
author_curate_reward""
vote details (6)
@portugalcoin ·
Please correct the repository for angular js.
After this correction I see the tutorial again.

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
properties (22)
authorportugalcoin
permlinkre-chri5h-consuming-github-api-using-angular-js-20180520t115617524z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-05-20 11:56:18
last_update2018-05-20 11:56:18
depth1
children1
last_payout2018-05-27 11:56:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length263
author_reputation599,460,462,895,094
root_title"Consuming GitHub API using Angular JS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id56,696,598
net_rshares0
@chri5h ·
Thank you for the correction @portugalcoin. I have effected the corrections, I really appreciate it.
properties (22)
authorchri5h
permlinkre-portugalcoin-re-chri5h-consuming-github-api-using-angular-js-20180520t125409479z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["portugalcoin"],"app":"steemit/0.1"}
created2018-05-20 12:54:15
last_update2018-05-20 12:54:15
depth2
children0
last_payout2018-05-27 12:54:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length100
author_reputation2,291,303,072,819
root_title"Consuming GitHub API using Angular JS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id56,703,747
net_rshares0
@portugalcoin ·
Thank you for your contribution.
While I liked the content of your contribution, I would still like to extend one advice for your upcoming contributions: 

- There are parts of the code that have little explanation, try to explain as much as possible.

Looking forward to your upcoming tutorials.


Your contribution has been evaluated according to [Utopian rules and guidelines](https://utopian.io/rules), as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post,[Click here](https://review.utopian.io/result/8/21143323)

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
properties (22)
authorportugalcoin
permlinkre-chri5h-consuming-github-api-using-angular-js-20180520t130225736z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://utopian.io/rules","https://review.utopian.io/result/8/21143323","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-05-20 13:02:24
last_update2018-05-20 13:02:24
depth1
children1
last_payout2018-05-27 13:02:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length773
author_reputation599,460,462,895,094
root_title"Consuming GitHub API using Angular JS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id56,704,756
net_rshares0
@chri5h ·
Thanks alot for the approval. I will adhere to your suggestions in upcoming contributions.
properties (22)
authorchri5h
permlinkre-portugalcoin-re-chri5h-consuming-github-api-using-angular-js-20180520t133538807z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-05-20 13:35:48
last_update2018-05-20 13:35:48
depth2
children0
last_payout2018-05-27 13:35:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length90
author_reputation2,291,303,072,819
root_title"Consuming GitHub API using Angular JS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id56,708,965
net_rshares0
@utopian-io ·
Hey @chri5h
**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Contributing on Utopian**
Learn how to contribute on <a href='https://join.utopian.io'>our website</a> or by watching <a href='https://www.youtube.com/watch?v=8S1AtrzYY1Q'>this tutorial</a> on Youtube.

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-consuming-github-api-using-angular-js-20180521t061010z
categoryutopian-io
json_metadata"{"app": "beem/0.19.29"}"
created2018-05-21 06:10:12
last_update2018-05-21 06:10:12
depth1
children0
last_payout2018-05-28 06:10:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length503
author_reputation152,955,367,999,756
root_title"Consuming GitHub API using Angular JS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id56,830,109
net_rshares0