Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend externo #17

Open
danielfscastro opened this issue Oct 17, 2016 · 4 comments
Open

Backend externo #17

danielfscastro opened this issue Oct 17, 2016 · 4 comments

Comments

@danielfscastro
Copy link

estou tentando carregar um objeto no meu json externo mas não está funcionando, alguém poderia me ajudar.

expressjs

@danielfscastro
Copy link
Author

var express = require('express'),
app = express(),
//log requests to the console (express4)
morgan = require('morgan'),
// pull information from HTML POST (express4)
bodyParser = require('body-parser'),
// simulate DELETE and PUT (express4)
methodOverride = require('method-override'),
http = require('http');

// set .html as the default extension
app.set('view engine', 'html');
app.set('views',__dirname + '/views');

// Block the header from containing information
// about the server
app.disable('x-powered-by');

// Defines the port to run on
app.set('port', process.env.PORT || 3000);

//Carrega tudo que esta dentro da pasta public
//ex: http://localhost:3000/static/img/image001.png
//ex: http://localhost:3000/img/image001.png
//app.use('/static', express.static(__dirname + '/public'));
//app.use(express.static('public'));
app.use('/manutencao-eventos', express.static(__dirname + '/public'));
app.use('/manutencao-eventos/node_modules', express.static(__dirname + '/node_modules'));
// log every request to the console
app.use(morgan('dev'));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({'extended':'true'}));
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());

app.all('', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '
');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});

// Define some routes. app.get receives a path and a
// function and it defines our routes. The path isn't
// case sensitive and doesn't care about trailing path
// information.
// The req object represents the HTTP request and
// contains the query string, parameters, body, header
// The res object is the response Express sends
// when it receives a request
app.get('/manutencao-eventos', function(req, res){
res.sendFile(__dirname + '/index.html');
//res.render('index');
});

app.get('/manutencao-eventos/views/footer.html', function(req, res){
res.sendFile(__dirname + '/views/footer.html');
});

app.get('/manutencao-eventos/eventos', function(req, res) {
res.sendFile(__dirname + '/backend/eventos.json');
});

app.post('/manutencao-eventos/eventos', function(req, res) {
// var aaa = res.sendFile(__dirname + '/backend/eventos.json');
// console.log(aaa);
console.log(req.body);
res.send(req.body);

});

app.get('/manutencao-eventos/tiposDeEvento', function(req, res) {
res.sendFile(__dirname + '/backend/tiposDeEvento.json');
//res.json(operadoras);
});

app.listen(app.get('port'), function(){
console.log('Express started on http://localhost:' +
app.get('port') + '; press Ctrl-C to terminate');
});

@danielfscastro
Copy link
Author

<title>Manutenção de Eventos</title> <style> .jumbotron{ width: 900px; text-align: center; margin-right: auto; margin-left: auto; margin-top: 50px; } .table{ margin-top: 20px; border-collapse: separate; border-spacing: 3px; width: 850px; margin-left: 25px; } .form-control { margin-bottom: 5px; } .selecionado > td{ background-color: yellow; } .negrito{ font-weight: bold; } /\* marca a primeira linha da tabela com a cor desejada*/ .table-striped > tbody > tr:first-child > th{ background-color: green; border-radius: 5px; padding: 5px; color: white; } .busca{ width: 850px; margin-left: 25px; }
.classOrdem{
text-decoration:none;
color: white;

}
a:hover {
text-decoration: none ; 
color: white; 
}
</style> <script src="node_modules/angular/angular.min.js"></script> <script src="node_modules/angular-messages/angular-messages.js"></script> <script> angular.module('manutencaoEventos', ['ngMessages']); angular.module('manutencaoEventos').controller('manutencaoEventosCtrl',function($scope,$http){ $scope.app = 'Manutenção de Eventos' $scope.eventos = [];
      $scope.tiposDeEventos = [];

      var carregarEventos = function(){
          $http.get("http://localhost:3000/manutencao-eventos/eventos").success(function(data,status){
              $scope.eventos = data;

          });
      };

      var carregarTiposDeEventos = function(){
          $http.get("http://localhost:3000/manutencao-eventos/tiposDeEvento").success(function(data,status){
              $scope.tiposDeEventos = data;
          });
      };

       $scope.addEvent = function (evento){
           $http.post("http://localhost:3000/manutencao-eventos/eventos",evento).success(function(data){
               delete $scope.evento; //deleta o evento
               $scope.manutencaoEventosForm.$setPristine(); //reseta as mensagens de erro
               carregarEventos();
           });

            //$scope.eventos.push(evento); //adiciona o objeto no array

        };
        //retorna os eventos que não foram marcados para remoção utilizando filter
        $scope.removeEvents = function (eventos){
            $scope.eventos =  
            eventos.filter(function (evento){
                if (!evento.isRemove) return evento;
            });
        };

        //Se existir algum evento para ser removido mostra o botão de apagar 
        $scope.isSelectedEvent = function (eventos) {
            return eventos.some(function (evento){
                return evento.isRemove;
            }); 
        }
        $scope.orderBy = function (campo) {
            $scope.criteryOrder = campo;
            $scope.directionOrder = !$scope.directionOrder;
        };

        carregarEventos();
        carregarTiposDeEventos();
  });
</script>

{{app}}

Preencha o campo data original
Campo data deve ter o formato dd/mm/yyyy
Campo data deve ter o formato brasileiro de dd/mm/yyyy - regex validation
    <!-- forma de validacao usando ngMessages para agrupar varias mensagens referentes ao mesmo campo, 
    importar o angular-messages.js e referenciar o modulo angular.module('manutencaoEventos', ['ngMessages']);-->
    <div ng-messages="manutencaoEventosForm.type.$error" ng-show="manutencaoEventosForm.type.$dirty" ng-class="{'alert alert-danger' : manutencaoEventosForm.type.$invalid}" role="alert">
        <div ng-message="required" >Selecione o Tipo de Evento</div>    
    </div>
    <!-- forma de validacao usando $invalid e $valid.-->
    <div ng-show="manutencaoEventosForm.isIncorporaJuros.$invalid && manutencaoEventosForm.isIncorporaJuros.$dirty" class="alert alert-danger">Preencha o campo indicando se incorpora juros</div>

    <input type="text" class="form-control busca" name="criterio" ng-model="criterio" placeholder="Busca por qualquer coluna?" />
    <input type="text" class="form-control busca" name="criterioTipo" ng-model="criterioTipo" placeholder="Busca somente por tipo de evento?" />

    <table class="table table-striped" ng-show="eventos.length > 0">
        <tr>
            <th><a class="classOrdem" ng-click="orderBy('date')">Data Original</a></th>
            <th><a class="classOrdem" ng-click="orderBy('type.eventType')"> Tipo Evento</a></th>
            <th>Incorpora Juros?</th>
            <th>Excluir?</th>
        </tr>
        <!-- O primeiro filtro, filtra tudo dentro de evento. 
             O segundo filtro, filtra um atributo dentro de um objeto que esta dentro de outro objeto exemplo evento tem um objeto type que tem seus atributos.  -->
        <tr ng-class="{'selecionado negrito': evento.isRemove}" ng-repeat="evento in eventos | filter:criterio | filter:{type:{eventType:criterioTipo}} | orderBy:criteryOrder:directionOrder">
        <td>{{evento.date | date: 'dd/MM/yyyy'}}</td>
        <td>{{evento.type.eventType | uppercase}}</td>
        <td>{{evento.isIncorporaJuros}}</td>
        <td><input type="checkbox" ng-model="evento.isRemove"></input></td>
        </tr>
    </table> 
    <hr/>
    <form name="manutencaoEventosForm">
    <table class="table">
        <tr>
        <td><input class="form-control" type="text" ng-model="evento.date" name="date" ng-required="true" ng-minlength="10" ng-pattern="/^\d{2}\/\d{2}\/\d{4}$/"/></td>
        <td><!--select class="form-control" ng-model="evento.type" ng-options="tipoDeEvento.eventType group by tipoDeEvento.isFinal for tipoDeEvento in tiposDeEventos" >
                <option value="">--- Selecione um evento ---</option>
            </select-->
            <select class="form-control" ng-model="evento.type" name="type" ng-options="tipoDeEvento.eventType for tipoDeEvento in tiposDeEventos | orderBy:'eventType'" ng-required="true">
                <option value="">--- Selecione um evento ---</option>
            </select>
        </td>
        <td><input class="form-control" type="text" ng-model="evento.isIncorporaJuros" name="isIncorporaJuros" ng-required="true"/></td>
        <td>&nbsp;</td>
        </tr>
    </table>
    </form>
    <button class="btn btn-primary" ng-click="addEvent(evento)" ng-disabled="!evento.date || !evento.type">Adicionar Evento</button>
    <button class="btn btn-danger" ng-click="removeEvents(eventos)" ng-show="isSelectedEvent(eventos)" >Apagar Eventos</button>
</div>
<div ng-include="'views/footer.html'">
    <!--
        filtros: 
        number ex:(100 | number, 100 | number:2 -> casas decimais), 
        currency -> é possivel baixar o angular-locale e depois importar o script.
        limitTo:3 - limita o numero de caracteres em uma string

    -->
</div>

@danielfscastro
Copy link
Author

eventos.json
[
{"date": "new Date(2016,9,11)" , "type": {"eventType": "Pagamento de Juros", "id": 1, "isFinal": "NÃO"}, "isIncorporaJuros": false, "isRemove": false },
{"date": "new Date(2012,9,11)" , "type": {"eventType": "Vencimento (Resgate)", "id": 2, "isFinal": "SIM"}, "isIncorporaJuros": true, "isRemove": false },
{"date": "new Date(2011,9,11)" , "type": {"eventType": "Pagamento de Amortização", "id": 3, "isFinal": "NÃO"}, "isIncorporaJuros": false, "isRemove": false }
]

@danielfscastro
Copy link
Author

tiposDeEvento.json
[
{"eventType" : "Pagamento de Juros" , "id": 1, "isFinal": "NÃO" },
{"eventType" : "Vencimento (Resgate)" , "id": 2, "isFinal": "SIM" },
{"eventType" : "Pagamento de Amortização", "id": 3, "isFinal": "NÃO" }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant