Inject a service or factory into a controller in angular.js

0

I'm getting into the world of angular, and trying to inject a service or factory into a controller, but I get errors.

I make a call $ http.post using a controller

var app;     

app = angular.module('AppUPC',[]);

app.controller('formulario', ['$scope', '$http', '$httpParamSerializer', 
    function ($scope, $http, $httpParamSerializer){

    $scope.login = function(){

        var datos;

        datos = {

            Usuario: $scope.usuariotxt,
            Password: $scope.passwordtxt

        };

        console.log(datos);          

        var url, method;

        url = 'http://190.109.185.138/Apipedro/api/login';
        method = 'POST';

        $http.post(url, $httpParamSerializer(datos), {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

        }).then(function success(response) {

            $scope.persons = response.data;
            console.log($scope.persons);

        }, function error(response) {

            $scope.status = response.status;
            console.log($scope.status);

        });

     }; 

 }]);

Then I divided responsibilities in this way using a service

controller

var app;     

    app = angular.module('AppUPC',[]);

    app.controller('formulario', ['$scope', 'ObtenerDatos', function ($scope, ObtenerDatos){

        $scope.login = function(){

            var datos, usuario;

            datos = {

                Usuario: $scope.usuariotxt,
                Password: $scope.passwordtxt

            };

            usuario = ObtenerDatos;

            console.log(usuario);     

       };         

    }]);

service

app.service('ObtenerDatos',['$scope', '$http', '$httpParamSerializer', function ($scope, $http, $httpParamSerializer){

        $scope.peticion = function (datos){

            var url, method;

            url = 'http://190.109.185.138/Apipedro/api/login';
            method = 'POST';

            $http.post(url, $httpParamSerializer(datos), {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

            }).then(function success(response) {

                return response.data;

            }, function error(response) {

                return response.status;

            });

        };

}]);

Error

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- ObtenerDatos
    
asked by Pedro Miguel Pimienta Morales 22.02.2016 в 18:27
source

2 answers

1

What I notice is that in addition to injecting the scope to the service which would be incorrect, you do not define well how the data returns the service.

Analyze how the implementation of the service changes

app.service('ObtenerDatos',['$http', '$httpParamSerializer', function ($http, $httpParamSerializer){

        function Autenticacion(datos){

            var url = 'http://190.109.185.138/Apipedro/api/login';

            return $http.post(url, $httpParamSerializer(datos), {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

            });

        };

        return {
            Autenticacion: Autenticacion
        };

}]);

It is important how the return is defined at the end of the service indicating the functionality that exposes You will also see how a promise of http is returned to use it from the controller

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

app.controller('formulario', ['$scope', 'ObtenerDatos', function ($scope, ObtenerDatos){

    $scope.login = function(){

        var datos = {
            Usuario: $scope.usuariotxt,
            Password: $scope.passwordtxt
        };

        var usuario = ObtenerDatos.Autenticacion(datos)
                                .then(function(result){
                                    console.log(result);
                                }, function(err){
                                    console.log(err);
                                }});



   };         

}]);

In the controller, you define the functions of the then , obtaining the answer of the invocation to the service

    
answered by 23.02.2016 / 11:49
source
1

You can not inject the scope into a service. A service is initialized once upon entering the page, and at that moment there is no scope that you want to inject. You could inject $rootScope , but it would not help in your case. Change your service to:

app.service('ObtenerDatos',['$http', '$httpParamSerializer', function ($http, $httpParamSerializer){

            return function (datos){

                var url, method;

                url = 'http://190.109.185.138/Apipedro/api/login';
                method = 'POST';

                return $http.post(url, $httpParamSerializer(datos), {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

                }).then(function success(response) {

                    return response.data;

                }, function error(response) {

                    return response.status;

                });

            };

    }]);

And the code you call the service change it to:

ObtenerDatos(datos).then(function (resultado) {
    console.log(resultado);
});

I would also recommend that the name of the service start with a lowercase (it's the usual convention in angular), and you probably need to review the use of promises for what I've seen you've done in the code (the reason I've used it .then when I called the service).

    
answered by 22.02.2016 в 19:07