How to query a web api by passing parameters using Angularjs?

Asked

Viewed 924 times

4

I have the current script:

(function () {
    'use strict';

    var numeros = angular.module("myModule", [])
    .controller("myController", function ($scope, $http, $log) {

        var sucessoCalBack = function (response) {
            $scope.detalhes = response.data;
        };

        var erroCalBack = function (response) {
            $scope.error = response.data;
        };

		//não está funcionando
        $scope.getAll = function (idusuario) {
            var config = {
                method: 'GET',
                url: 'http://www.sistemaguardiao.com.br/webapi/api/AspNetWebApi/consulta/JogosPorID/' + idusuario
            };
            $http(config).then(sucessoCalBack, erroCalBack);
        };

		
        //assim funciona, passando o parametro direto 
        $http({
            method: 'GET',
            params: { idusuario: 5 },
            url: 'http://www.sistemaguardiao.com.br/webapi/api/AspNetWebApi/consulta/JogosPorID/5'})
            .then(sucessoCalBack,erroCalBack);
        });



})();

I have the HTML:

<!DOCTYPE html>
<html ng-app="myModule">
<head>
    <meta charset="utf-8" />
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8">
    <!-- Bootstrap-->
    <link href="Content/bootstrap-responsive.min.css" rel="stylesheet">
    <link href="Content/bootstrap.min.css" rel="stylesheet" media="screen" />
    <link href="Content/style.css" rel="stylesheet" media="screen" />
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/Script.js"></script>


</head>


<body ng-controller="myController">

            <div class="container">
                <br><br>

                <table class="table table-striped table-bordered table-hover table-condensed">
                    <thead>
                        <tr>
                            <th>idjogodetalhe</th>
                            <th>nJogo</th>
                            <th>valor</th>
                            <th>total</th>
                            <th>idusuario</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="success" ng-repeat="detalhe in detalhes" >
                            <td>{{detalhe.idjogodetalhe}}</td>
                            <td>{{detalhe.nJogo}}</td>
                            <td>{{detalhe.valor}}</td>
                            <td>{{detalhe.total}}</td>
                            <td>{{detalhe.idusuario}}</td>

                        </tr>
                    </tbody>
                </table>

            <form action="">
                <div class="input-append">
                     <input class="input-xlarge" type="text" placeholder="Consultar usuário..." required>
                     <button class="btn btn-primary  " ng-click="getAll(5)" >Listar Dados</button>
                </div>
            </form>



            </div>



            <!--javascript-->
            <script src="http://code.jquery.com/jquery.js"></script>
</body>
</html>

I have the current answer:

inserir a descrição da imagem aqui

  • passes the parameter in the URL

1 answer

1

I recommend creating a service to work with API's, leave everything on controller is not a good practice.

Ex:

angular.module("oraculo").factory("colaboradorAPI", function ($http, config) {

    var _getColaboradores = function(id){
        return $http.get(config.baseURL + "/SistemaWS/colaborador/colaboradores/" + id);
    };

    return {
        getColaboradores: _getColaboradores

    };
});

Do not forget to put the path of this service on index.html.

Then in the Controller you can do something like this:

 var carregarInicial = function(id) {
     //Passa o id como parametro pro método que está no service
     colaboradorAPI.getColaboradores(id) then(function(res) {
         $scope.lista = res.data;
     }, function(err) {
         alert('Failed: ' + err);
     });
 }

You have to inject the service into your controller, ex:

angular.module("oraculo").controller("colaboradorController", function($scope, colaboradorAPI)

I did not do a better implementation because I am a little short of time, I believe you can adapt this example according to your need, if you can not later improve the answer.

  • Hello, I was just passing of curious @Techies, why is not indicated to communicate the API via controller?

  • 1

    @pmargreff because it can generate a "repetition" of code, so it is simpler to create a service and whenever you need to call this service in the controller.

  • 1

    I get it, it makes great sense, it helps me in some situations, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.