Angularjs. Services. $http service

Home » Tutorials » JavaScript » Angularjs. Services. $http service
Today we’ll consider services in angular on the example of $http service. $http is one of the powerful and important services in angular. It lets developer to communicate with server. Also it helps to make cross domain requests.
In some cases services are similar on javascript build-in objects. For example, $http service is analog of XMLHttpRequest (XHR) in javascript. But there is one important difference – services in angular are not global objects. It’s not the same in javascript.
$http service has got several methods, which illustrate requests types:

  • $http.get(url, config)
  • $http.post(url, data, config)
  • $http.put(url, data, config)
  • $http.delete(url, config)
  • $http.jsonp(url, config)
  • $http.head(url, config)
  • $http.patch(url, data, config)

Accordingly, each of these methods accepts 2 or 3 parameters: url – request address; data – data, which you send to the server; config – additional information for request.
It’s not required to call some of these methods to do request. You can make request, call $http as a method, pass to it config object. In the code below I shew both ways.
Also I notice, with $http it is possible to make cross domain requests. For this $http has got jsonp method.
You cand read more about $http service here
Homework for you will be next task – you must make post request (save data from our app form).
Send me your results to mail@kamil-abzalov.ru

Code lesson
<!DOCTYPE html>
<html ng-app="playersApp">
    <head>
        <meta charset="utf-8">
        <title></title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <style>
            /*input.ng-invalid-required {
                border: 1px solid red;
            }*/
        </style>
    </head>
    <body>

        <div class="container" ng-controller="playerCtrl">
            <div class="row">
                <div class="col-md-12">
                    <form class="form-horizontal" name="addPlayerForm" novalidate>
                        <legend>Список футболистов</legend>
                          <div class="form-group" ng-class="{'has-error': addPlayerForm.pName.$error.required && addPlayerForm.pName.$dirty}">
                            <label for="playerName" class="col-sm-4 control-label">Имя игрока</label>
                            <div class="col-sm-8">
                              <input type="text" required name="pName" ng-model="playerName" class="form-control" id="playerName" placeholder="Имя игрока">
                              <span class="error" ng-show="addPlayerForm.pName.$dirty && addPlayerForm.pName.$error.required">Введите имя игрока!</span>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="playerTeam" class="col-sm-4 control-label">В какой команде играет</label>
                            <div class="col-sm-8">
                              <input type="text" name="pTeam" ng-model="playerTeam" class="form-control" id="playerTeam" placeholder="В какой команде играет">
                            </div>
                          </div>
                          <div class="form-group" ng-class="{'has-error': addPlayerForm.pCountry.$error.required && addPlayerForm.pCountry.$dirty}">
                            <label for="playerCountry" class="col-sm-4 control-label">Гражданство</label>
                            <div class="col-sm-8">
                                <input type="text" required name="pCountry" ng-model="playerCountry" class="form-control" id="playerCountry" placeholder="Гражданство">
                                <span class="error" ng-show="addPlayerForm.pCountry.$dirty && addPlayerForm.pCountry.$error.required">Игрок не может быть без гражданства!</span>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="playerGoals" class="col-sm-4 control-label">Сколько голов забил</label>
                            <div class="col-sm-8">
                              <input type="text" name="pGoals" ng-model="playerGoals" class="form-control" id="playerGoals" placeholder="Сколько голов забил">
                            </div>
                          </div>
                          <div class="form-group">
                              <div class="col-sm-8 col-sm-offset-4">
                                  <button ng-disabled="addPlayerForm.pName.$invalid || addPlayerForm.pCountry.$invalid" ng-click="addPlayer(playerName, playerTeam, playerCountry, playerGoals)" class="btn btn-default">Добавить</button>
                              </div>
                          </div>
                    </form>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <input type="text" name="pSelect" ng-model="selectPlayers" class="form-control">
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th ng-click="sortByName('name')">Игрок</th>
                                <th>Команда</th>
                                <th>Национальность</th>
                                <th>Сколько голов забил</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="player in players | filter:selectPlayers">
                                <td>{{player.name}}</td>
                                <td>{{player.team}}</td>
                                <td>{{player.country}}</td>
                                <td>{{player.goals}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <script src="angular.js"></script>
        <script>
            var app = angular.module("playersApp", []);

            var model = [];


            app.controller("playerCtrl", function($scope, $http){
                $scope.players = model;
                $scope.orderByFunction = function(player){
                    return parseInt(player.goals);
                };
                $scope.addPlayer = function(playerName, playerTeam, playerCountry, playerGoals) {
                    $scope.players.push({name: playerName, team: playerTeam, country: playerCountry, goals: playerGoals});
                };

                $scope.sortByName = function(p) {
                    $scope.nameSorting = p;
                };

                /*$http({
                    method: "GET",
                    url: "players.json"
                }).then(function successResp(response) {
                    $scope.players = response.data.players;
                    console.log($scope.players);
                }, function errorResp(response) {
                    console.log(response);
                });*/

                $http.get("players.json").then(
                    function successResp(response) {
                        $scope.players = response.data.players;
                        console.log($scope.players);
                    }
                )

            });

        </script>

    </body>
</html>
Code lesson
<!DOCTYPE html>
<html ng-app="test">
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body ng-controller="vkCtrl">

		<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
		<script type="text/javascript">
			var app = angular.module("test", []);
			app.controller("vkCtrl", function($http, $scope, $sce) {
				/*$http({
        			url: 'https://api.vk.com/method/users.get',
        			method: "JSONP",
        			responseType: "json",
			        params: {
			            callback: "JSON_CALLBACK",
			            "user_id": 90759251,
			            "v": "5.60"
			        }
    			})
				.success(function(data, status, headers, config) {
					console.log(data.response);
    			}).error(function(data, status, headers, config) {
        			console.log("error" + data);
    			});*/

				$http.jsonp("https://api.vk.com/method/users.get?user_ids=90759251&fields=bdate&v=5.68&callback=JSON_CALLBACK")
				.then(function(data){
   					console.log(data);
				});

			});
		</script>
	</body>
</html>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This