javascriptangularjsangular-servicesangular-controller

How to create service and use it in controller


I am having a simple login form and I want to validate user upon successful HTTP request and it works fine. however, I've written all the code in the controller itself and I don't want that. i am new to angularjs so i have trouble creating service. so I need to create service for my logic. can anyone create service for the logic in the controller so that code works exactly same? sample.html(for now it only prints username, password, and status code of response)

<html>
<head>
<script src="angular.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="mycontroller">
    Username <input type="text" ng-model="login" /><br><br> Password <input 
type="password" ng-model="pass" /><br>
    <button type="submit" ng-click="myfunc()">Login</button>
    <center>User name is {{ login }}, password is{{pass}}<br>
{{success.code}}
</div>
</body>
</div>
</body>
</html>

Controller

var app = angular.module("myapp", []);
app.controller("mycontroller", function($scope, $http, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
    var obj = {
        login_id: $scope.login,
        password: $scope.pass
    }
    var mydata = JSON.stringify(obj);
    $http({
        method: 'POST',
        url: "http://myapiurl.com/signin/",
        headers: {
            "authorization": "oauth mytoken",
            'Access-Control-Allow-Origin': '*'
        },
        data: mydata
    }).then(function(response) {
            console.log(response)
            $scope.success = response.data;
        },
        function(reason) {
            $scope.error = reason.data
            console.log(reason);
            $log.info(reason.data);
        });
}
});

Solution

  • Create a myService factory and create a function to send http req and return the response.

    app.factory('myService', function($http) {
    
        return {
            httpReq: function(data) {
                return $http({
                    method: 'POST',
                    url: "http://myapiurl.com/signin/",
                    headers: {
                        "authorization": "oauth mytoken",
                        'Access-Control-Allow-Origin': '*'
                    },
                    data: data
                })
            }
        }
    });
    

    Now call it from the controller.

    app.controller("mycontroller", function($scope, myService, $log) {
        $scope.login = "";
        $scope.pass = "";
        $scope.myfunc = function() {
            var obj = {
                login_id: $scope.login,
                password: $scope.pass
            }
            var mydata = JSON.stringify(obj);
            myService.httpReq(mydata)
                .then(function(response) {
                        console.log(response)
                        $scope.success = response.data;
                    },
                    function(reason) {
                        $scope.error = reason.data
                        console.log(reason);
                        $log.info(reason.data);
                    });
        }
    });