【问题标题】:make a post request out of an angular ui-modal从角度 ui-modal 发出 post 请求
【发布时间】:2015-10-13 17:33:31
【问题描述】:

我已经制作了一个角度模态作为指令。我的目标是使用给定的表单数据向 json 文件发出 post 请求。我不确定如何设置发布请求。我读到 $http 为我处理 JSON.stringify() 所以我不需要为帖子配置数据。我也想知道我是否需要设置我的标题?以下是我拥有的大部分数据。

我创建了一个 json 文件来保存一个数组,我从中得到了一个啤酒列表。

addBeer() 函数是我理想的在工厂中发出 post 请求的地方

就目前而言,我正在像这样设置我的功能

function addBeer() {
            return $http.post(url,{
                data: JSON.stringify({}),
                headers: {'Content-Type': 'application/json'}
            })
            .then(function(response) {
                console.log('response', response);
            })


        }

这将是工厂的一部分。在整个工厂中,我遵循 John papa 风格指南。 getBeerList() 正在获取整个 json 文件,而 getBeer() 正在获取我正在寻找的每个啤酒。

   (function() {
    'use strict';
    angular
        .module('beerApp.services.beerList',[])
        .factory('beerListFactory', beerListFactory);

        beerListFactory.$inject = ['$http', '$log'];

        function beerListFactory($http, $log) {
            var url = './app/Services/IBU_list.json';

            return {
                getBeerList: getBeerList,
                getBeer: getBeer,
                addBeer: addBeer

            }

            function getBeerList(){

                return $http.get(url, {catch: true})
                    .then(getBeerListComplete)
                    .catch(getBeerListFailed);

                    function getBeerListComplete(response) {

                        return response.data;
                    }

                    function getBeerListFailed(error) {
                        console.log('error', error);
                    }
            }

            function getBeer(id) {
                return $http.get(url, {
                    catch: true
                })
                .then(getBeerComplete)

                function getBeerComplete(response) {
                    console.log('promise', id);
                    console.log('response', response.data.length);
                    var data = response.data;
                    for(var i =0, len=data.length;i<len;i++) {
                        console.log(typeof data[i].id)
                        if(data[i].id == parseInt(id)) {
                            console.log('data i',data[i]);
                            return data[i];
                        }
                    }
                } // end of getBeerComplete
            } //end of getBeer

            function addBeer() {
                return $http.post(url,{
                    data: JSON.stringify({}),
                    headers: {'Content-Type': 'application/json'}
                })
                .then(function(response) {
                    console.log('response', response);
                })


            }
        } // end of beer Factory
})();

总体目标是推入一个对象设置如下的 json 数组:

{
"id" : "4",
"BeerStyle": "American Light Lager",
"IBU": "8-17",
"list" : {"drinks": []}

},

表格中的每种饮品都应放入“饮品”数组

在我的 Modal Instance Contrl 内部,我正在检查我使用

设置的表单值
vm.newBeer = {};

这是我注释掉 addBeer 函数的函数,但这是我对发布请求最理想的做法

function ModalInstanceCtrl( $scope,$modalInstance) {

            var vm = this;
            vm.ok = ok; 
            vm.cancel = cancel; 
            vm.newBeer = {};
            // vm.addBeer = function() {

            // }

            function ok () {
                console.log('new beer', vm.newBeer);
                // console.log('IBU',$scope.IBU);
                console.log('clicked');
                $modalInstance.close();
            };

            function cancel() {
                console.log('beer', vm.newBeer);

                console.log('clicked');
                $modalInstance.dismiss('cancel');
            };
        } 

我正确地获取了控制台内部的值

<input type="text" class="form-control" placeholder="beer" ng-model="vm.newBeer.beerName">

在我的指令中,我正在调用我为单一啤酒发出的 get 请求。我这样做是为了确保我已经设置好并且可以连接到控制器。我认为发布请求将在解决方案中进行。

   function ModalController($modal, $log , $scope, beerListFactory, $stateParams) {
            var vm = this;

            vm.animationsEnabled = true;
            vm.open = open;

            function open() {
                var modalInstance = $modal.open({
                    animation: vm.animationsEnabled,
                    templateUrl: 'app/components/modal/modal.html',
                    controller: ModalInstanceCtrl,
                    controllerAs: 'vm',
                    bindToController: true,
                    size: 'lg'
                    // resolve: {
                    //  title: function() {
                    //      return 'training Info';
                    //  }
                    // }            
                });
                modalInstance.result.then(function(selectedItem) {
                    $log.info('beer in modal',beerListFactory.getBeer($stateParams.beerId) );

                    console.log("Confirmed: "+ selectedItem);
                    $scope.selectedItem = selectedItem;
                }, function() {
                    $log.info('modal dismissed at: ' + new Date());
                });
            };

【问题讨论】:

  • 将 addBeer 更改为:function addBeer() { return $http.post(url,{ data: JSON.stringify({}), headers: {'Content-Type': 'application/json' } }) .then(function(response) { console.log('Sucess: ', response); }, function(error){ console.log('Error: ', response); }); },这个节目在帖子中出现错误
  • @EmirMarques 我希望得到一个不允许的方法。这就是我得到的。我不确定如何设置它。我需要将 newBeer 对象推送到分配给饮料的数组中。

标签: json angularjs http bootstrap-modal


【解决方案1】:

如果您使用 JSON,我建议使用 Angular 的 $resource 工厂。

返回的资源对象具有提供的操作方法 无需与低层交互的高层行为 $http 服务。

您可以使用Beer.query()Beer.save(),而不是$http.get()$http.post()$resource 专为像您这样的服务而设计。

【讨论】:

    【解决方案2】:

    终于成功了。

    HTML

    <!--MODAL WINDOW for item details -->
         <script type="text/ng-template" id="itemModalContent.html">
            <div class="modal-dialog " ng-class="{fadeOut: startFade}" ng-hide="hidden">
                 <div class="modal-content">
                      <div class="modal-header">
                           <button type="button" class="cancel right button" data-dismiss="modal" aria-hidden="true" ng-click="cancel()"><i class="fa fa-close"></i></button>
                           <span class="item-name">{{item.name}}</span>
                      </div>
                      <div class="modal-body">
                           <p class="description">{{item.description}}</p>
                           <input type="hidden" ng-model="item.uniqueid" id="itemid" value="{{item.courseid}}" name="itemid"/>
                           <p class="response"> {{PostDataResponse}}</p>
                           <p class="error"> {{ResponseDetails}}</p>
                       </div>
                       <div class="modal-footer">
                            <button type="button" class="button cancel btn-default" data-dismiss="modal" ng-click="cancel()">Cancel</button>
                            <button type="button" class="button ok btn-primary" ng-click="confirm()">Sign me up</button> 
                      </div>
                   </div>
               </div>
          </script>
    

    角度

    myApp.controller('itemModalInstanceCtrl', function ($http, $scope, $uibModalInstance, $timeout, item) {
        $scope.item = item;
        $scope.cancel = function () {
            $uibModalInstance.dismiss();
            $('.overlay').hide();
        };
    
        updateUrl = '<your URL to post to>';
    
        $scope.confirm = function () {
    
            var myItemId = $scope.item.uniqueid;
    
           // use $.param jQuery function to serialize data from JSON
            var data = $.param({
                uniqueid: myItemId
            });
                var config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                    }
                }
    
                $http.post(updateUrl, data, config)
                .success(function (data, status, headers, config) {
                    alert(JSON.stringify(data));
                    $scope.PostDataResponse = "You have signed up!";
                })
                .error(function (data, status, header, config) {
                    $('.response').addClass('error');
                    $scope.ResponseDetails = "data: " + data +
                            "<br />status: " + status +
                            "<br />headers: " + header +
                            "<br />config: " + config;
                });
                $timeout(function() {
                    $uibModalInstance.close({});
                    $('.overlay').hide();
                }, 3000);
        };
    
    });
    

    秘诀是不要将$scope$http 注入传递给confirm 函数,而是在函数内部完整 引用$scope.item.property。希望这对某人有帮助!

    【讨论】:

      猜你喜欢
      • 2014-02-16
      • 2018-11-10
      • 1970-01-01
      • 2016-12-17
      • 2014-03-08
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多