In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use AngularJS service to access external API. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
How to use AngularJS service to access external API
In addition to the ability to easily extend HTML, AngularJS also provides an easy way for us to interact with external API. In today's tutorial, we will explore how to use its services to interface with GitHub's API to create a simple library browser.
* step: prepare for work
Let's start with the following basic set of HTML templates:
GitHub Search
Now add the AngularJS script to the document:
After that, we can add this set of CCS styles to an inline or separate file:
* {- webkit-box-sizing: border-box;-moz-box-sizing: border-box; box-sizing: border-box; font-family: sans-serif;} body, html {margin: 0;} p {margin: 0;} input {width: 100%;} pre {white-space: pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap White-space:-Omurmurwrap. word-wrap: break-word;} div.repo {border-bottom: 1px solid; cursor: pointer;} # search, # repo, # user {float: left;} # search {width: 20%;} # repo {width: 60%;} # user {width: 20%;}
As you can see, there is no extra content, 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 lines of code into tags, and then we use it to display the contents of the README file-- because they usually come from GitHub Flavored Markdown, and some of them overlap with the list of user libraries.
Of course, you can add more styles to it to improve the visual effect of the results-but please note that the screenshots in this tutorial are based on the most basic design.
You can put the JavaScript code you need to write in this document or create a separate file for it in the future, but the separate file still needs to be under the AngularJS script.
Step 2: module
Now we can create a module for our application:
Var app = angular.module ('githubsearch', [])
Next, use the ngApp instruction to add it to the tag:
Step 3: controller
We also need to prepare a set of controllers for our applications. To simplify the creation process, we will prepare only one set of controllers for the application, so that we do not have to think about how to pass information between different controllers:
App.controller ('SearchController', function SearchController ($scope) {})
Step 4: basic services
We need to define our own GitHub service:
App.factory ('GitHub', function GitHub ($http) {return {};})
We will use the app.factory () method, which ensures that the returned object comes with several methods that will be used later. We will use the $http service to get the data from GitHub's API.
Step 5: search the base
The * methods in our service are responsible for searching the library using GitHub API. Using the service is very simple (this function can enter the object returned by the manufacturing function):
SearchRepos: function searchRepos (query, callback) {$http.get ('https://api.github.com/search/repositories', {params: {Q: query}}) .success (function (data) {callback (null, data);}) .error (function (e) {callback (e);});}
The $http.get () method is a shortcut to execute a GET request. The * parameter is the URL we want to access. The second parameter represents an object with options. All we need here is the params object-- it's a query parameter hash that will be added to the request (where the Q parameter belongs to the search string, you can click here for more information).
$http.get () returns a commitment. We can attach listeners to success () and error () and call the callback function accordingly.
Step 6: search bar
To use the function we defined in the previous steps, we need to add a search bar to our HTML. The relevant code is very simple, as follows:
{{repo.full_name}}
{{repo.description}}
We use the ngModel instruction to point the value in this input field to the Scope query variable and use ngKeyup to call the executeSearch () function after the user presses the enter key (so that $event.keyCode = = 13 will make a comparison). We can't use conditional statements in AngularJS expressions, but a simple logical operator (AND) is good enough to do this.
Under the input field, we use ngRepeat to display the search results. We will show the full name and description of the library (if you need to display something else, you can click here to see the available fields in the GitHub API documentation).
We also use ngClick to call the openRepo () function with the full name of the library so that we can display information about it. We will define this function later.
Step 7: use the search function
Now we can finally use the service we have created. First, add the GitHub parameter to the controller function (so that the service can be injected into the AngularJS):
App.controller ('SearchController', function SearchController ($scope) {
Now define the executeSearch () function:
$scope.executeSearch = function executeSearch () {GitHub.searchRepos ($scope.query, function (error, data) {if (! error) {$scope.repos = data.items;});}
As you can see, we call GitHub.searchRepos () from the search string from $scope.query, and then add the search results (from data.items) to the $scope.repos variable in the callback.
As long as we perform the above steps, we can successfully display the search results. Open our HTML file in a browser and try to search:
Step 8: get the data in the library
Now that we have the search function, we can display the information selected by the user in the library. Let's create another function that aims to obtain data from the library through our own service:
GetRepo: function getRepo (name, callback) {$http.get ('https://api.github.com/repos/'+ name) .success (function (data) {callback (null, data);}) .error (function (e) {callback (e);});}
The name passed to this function must be the full name (structure: author name, slash, library name-for example, angular/angular.js) because we need to pass it to GitHub API (click here for more instructions).
Step 9: get the README file in the library
The contents of the README file are not included in the data we obtained using the above function. Instead, you need to use another API to call and get, so we need to create the following function:
GetReadme: function getReadme (name, callback) {$http.get ('https://api.github.com/repos/'+ name +' / readme') .success (function (data) {callback (null, atob (data.content));}) .error (function (e) {callback (e);});}
This function is basically the same as the two we created before, except that the URL has been changed. We also use the atob () function to decode the contents of the README file because it uses the base64 encoding mechanism. You can click here to view the information related to getting the contents of the README file in the GitHub API documentation.
The reason we didn't cram these two requests into the same function is because some libraries don't have README files at all. If we forcibly combine the two, the application may fail as a result.
Step 10: display library information
We will display the full name of the library, the number of people who have viewed the library, and the README file in another element:
{{activeRepo.full_name}} Watched by {{activeRepo.watchers_count}} people. {{activeRepo.readme}}
We will store this information in the activeRepo variable in the controller Scope. As long as there is data to display, ngShow will display the element (if there is no data to display, we will only see the 'Watched by people' text, and no libraries have been selected).
Step 11: update the controller
We also need to update the controller to ensure that it actually gets the library data and incorporates it into the Scope. Let's create the openRepo () function we attached to the ngClick instruction:
$scope.openRepo = function openRepo (name) {GitHub.getRepo (name, function (error, data) {if (! error) {$scope.activeRepo = data; GitHub.getReadme (name, function (error, data) {if (! error) {$scope.activeRepo.readme = data } else {$scope.activeRepo.readme ='No README emergency payment;}});}});}
As you can see, we first use the GitHub.getRepo () method, check for errors, and then introduce this data into the activeRepo variable. Next, we get the README file-- if it doesn't exist, we need to alert the user of the situation.
Now you can run your application again and see how it actually works:
Step 12: get the user's library
In order to introduce more features into our application, we will display all available libraries for the holders of the selected libraries on the right side of the screen. This requires us to introduce another method into the service:
GetUserRepos: function getUser (name, callback) {$http.get ('https://api.github.com/users/'+ name +' / repos') .success (function (data) {callback (null, data);}) .error (function (e) {callback (e);});}
Its content is almost the same as the previous ones (you can click here for more information about this API request).
Step 13: display the user's library
This is basically equivalent to recreating the search bar mechanism in HTML, but what we really need to display is the library in the user name and user object, not the input field or the Scope itself:
{{user.login}} {{repo.name}}
{{repo.description}}
At this point, you should have a working AngularJS application-- it can get the GitHub library based on the search string. You can iterate over it further, such as adding more functionality to it or designing a completely different look and feel for it.
This is the end of the article on "how to access external API through AngularJS services". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.