如何创建服务并在控制器中使用它

时间:2018-01-22 15:18:36

标签: javascript angularjs angular-services angular-controller

我有一个简单的登录表单,我希望在成功的HTTP请求后验证用户,它运行正常。但是,我已经在控制器本身编写了所有代码而且我不想这样做。我是angularjs的新手,所以我在创建服务时遇到了麻烦。所以我需要为我的逻辑创建服务。任何人都可以为控制器中的逻辑创建服务,以便代码完全相同吗? sample.html (目前仅显示响应的用户名,密码和状态代码)

<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>

控制器

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);
        });
}
});

2 个答案:

答案 0 :(得分:2)

超级简单。首先创建一个注入$http模块的服务。创建一个可以调用的方法,该方法从$http模块返回promise。在此示例中,它是get方法。

app.service("ExampleService", function($http){

    this.ExampleRequest = function(){
       return $http.get('url');
    }

});

注入上面创建的服务,您可以调用您在服务中定义的功能。请注意,.then来自承诺。

app.controller("exampleCtrl", function($scope, ExampleService){

    $scope.onClick = function(){
       ExampleService.ExampleRequest().then(function(data){
        //  Do something with data
       });
    }

});

答案 1 :(得分:1)

创建一个myService工厂并创建一个函数来发送http req并返回响应。

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
            })
        }
    }
});

现在从控制器调用它。

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);
                });
    }
});