How to Use AngularJS service to access external APIs (1)

Source: Internet
Author: User

How to Use AngularJS service to access external APIs (1)

How to Use AngularJS service to access external APIs

In addition to the ability to easily expand HTML, AngularJS also provides a simple way to help us interact with external APIs. In today's tutorial, we will discuss how to use its services to connect with GitHub APIs and then create a simple library browser.

Step 1: Prepare

This basic HTML template is the starting point:

 
 
  1. <!DOCTYPE html> 
  2.     
  3.         <title>GitHub Search</title> 
  4.     
  5.     <body> 
  6.    
  7.     </body> 

Now add the AngularJS script to

 
 
  1. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script> 

After that, we can add this CCS style to a row or an independent file:

 
 
  1. * {  
  2.     -webkit-box-sizing: border-box;  
  3.     -moz-box-sizing: border-box;  
  4.     box-sizing: border-box;  
  5.     font-family: sans-serif;  
  6. }  
  7.    
  8. body, html { margin: 0; }  
  9. p { margin: 0; }  
  10. input { width: 100%; }  
  11.    
  12. pre {  
  13.     white-space: pre-wrap;  
  14.     white-space: -moz-pre-wrap;  
  15.     white-space: -pre-wrap;  
  16.     white-space: -o-pre-wrap;  
  17.     word-wrap: break-word;  
  18. }  
  19.    
  20. div.repo {  
  21.     border-bottom: 1px solid;  
  22.     cursor: pointer;  
  23. }  
  24.    
  25. #search, #repo, #user { float: left; }  
  26. #search { width: 20%; }  
  27. #repo { width: 60%; }  
  28. #user { width: 20%; } 

As you can see, there is no additional content, and only the most basic layout scheme is retained-the search bar is placed on the right, the library information is located in the center, and the user library is also placed on the right. We also need to package the corresponding code lines into the <pre> tag, later, we will also use it to display the content of the README file-because the content is usually from GitHub Flavored Markdown, and some of the code lines overlap with the user library list.

Of course, you can add a more practical style to improve the visual effect of the Results-but please note that the most basic design is adopted in this tutorial.

In the future, you can write JavaScript code in

Step 2: Module

Now we can create a module for our application:

 
 
  1. var app = angular.module('githubsearch', []); 

Next, use the ngApp command to add it to the <body> tag:

 
 
  1. <body ng-app="githubsearch"> 

Step 3: Controller

We also need to prepare a set of controllers for our own applications. To simplify the creation process, we will only prepare a set of controllers for the application, so that we do not have to consider how to transmit information between different controllers:

 
 
  1. app.controller('SearchController', function SearchController($scope) {  
  2.        
  3. }); 

Step 4: basic services

We need to define our GitHub service:

 
 
  1. app.factory('GitHub', function GitHub($http) {  
  2.     return {  
  3.    
  4.     };  
  5. });  

We will use the app. factory () method to ensure that the returned object will be accompanied by several methods that will be used later. We will use the $ http service to retrieve data from the GitHub API.

Step 5: search the database

The first method in our service is to use GitHub API to search for libraries. Using the service is very simple. This function can enter the objects returned by the manufacturing function ):

 
 
  1. searchRepos: function searchRepos(query, callback) {  
  2.     $http.get('https://api.github.com/search/repositories', { params: { q: query } })  
  3.         .success(function (data) {  
  4.             callback(null, data);  
  5.         })  
  6.         .error(function (e) {  
  7.             callback(e);  
  8.         });  

$ Http. get () is a shortcut for executing GET requests. The first parameter is the URL we want to access. The second parameter represents an object with options. Here we only need the params object -- it is a query parameter hash, which will be added to the request, where the q parameter is a search string. You can click here for more information ).

$ Http. get () returns a promise. We can append the listener to success () and error (), and call the callback function accordingly.

Step 6: search bar

To use the functions we have defined in the previous steps, we need to add a search bar in our own HTML. The related code is very simple, as shown below:

 
 
  1. <div id="search"> 
  2.     <input ng-model="query" placeholder="search" ng-keyup="$event.keyCode == 13 && executeSearch()"> 
  3.     <div class="repo" ng-repeat="repo in repos" ng-click="openRepo(repo.full_name)"> 
  4.         <strong>{{ repo.full_name }}</strong> 
  5.         <p>{{ repo.description }}</p> 
  6.     </div> 
  7. </div> 

You can use the ngModel command to direct the value in the input column to the Scope query variable. After you press the Enter key, you can use ngKeyup to call the executeSearch () function for $ event. keyCode = 13 ). We cannot use conditional statements in AngularJS expressions, but a simple logical operator AND is good enough to complete this task.

In the input field, we use ngRepeat to display the search results. We will display the complete name and description of the library. If you need to display other different content, you can click here to view the available domains in the GitHub API instructions ).

We also use ngClick to call the openRepo () function through the full name of the library, so that we can display the relevant information. We will define this function later.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.