如何在angularjs控制器中访问多个服务

时间:2018-08-23 12:38:18

标签: angularjs asp.net-mvc razor service aspnetboilerplate

在aspnetboilerplate .cshtml页面中,我们有

div ng-controller="app.views.automate as vm" 

,此角度控制器从asp.net mvc控制器访问automateService。 在该div内部,我们正在从另一个.cshtml文件加载部分视图,此处该文件应具有与Asp.net mvc控制器不同的服务(excelService)。如何实现。

Angular.js

(function () {

    var controllerId = 'app.views.automate';

    angular.module('app').controller(controllerId, [

        '$scope', 'abp.services.app.automate', function ($scope, automateService) {



            var vm = this;

            //Automate logic...

            //Model





            vm.currentStep = 1;

            vm.steps = [

                {

                    step: 1,

                    name: "First step",

                    template: "/App/Main/views/automate/step1.cshtml",

                    controller: 'app.views.excel as vm'

                },

                {

                    step: 2,

                    name: "Second step",

                    template: "/App/Main/views/automate/step2.cshtml"

                },

                {

                    step: 3,

                    name: "Third step",

                    template: "/App/Main/views/automate/step3.cshtml",

                    controller: 'app.views.capacity as vm'

                }

            ];         





            //Functions

            vm.gotoStep = function (newStep) {



                vm.currentStep = newStep;

                //$scope.ParseExcel();

            }

            vm.getStepTemplate = function () {



                for (var i = 0; i < vm.steps.length; i++) {

                    if (vm.currentStep == vm.steps[i].step) {

                        return vm.steps[i].template;



                    }

                }

            }

            vm.save = function () {

                //todo: save data...

                //vm.location['abq'].center

                //alert(vm.location.abq.center);

               // vm.enterCapacity(vm.location);

            }



            vm.enterCapacity = function () {



               // alert(vm.capacity.locations[0].center);



                automateService.calculateCapacity(vm.capacity).then(function () {

                    abp.notify.info(app.localize('SavedSuccessfully'));

                 });



            }   



            $scope.SelectedFileForUpload = null; //initially make it null

            $scope.BindData = null;

            $scope.showLoader = false;

            $scope.IsVisible = false;

            $scope.UploadFiles = function (files) {

                $scope.$apply(function () {

                    $scope.Message = '';

                    $scope.SelectedFileForUpload = files[0];

                });

            }



            vm.capacity = {

                locations: [

                    { city: "abq", center: 0, housing: 0 },

                    { city: "han", center: 0, housing: 0 },

                    { city: "udh", center: 0, housing: 0 },

                    { city: "dhn", center: 0, housing: 0 },

                    { city: "spp", center: 0, housing: 0 },

                    { city: "rt", center: 0, housing: 0 },

                    { city: "has", center: 0, housing: 0 },

                    { city: "jed", center: 0, housing: 0 },

                    { city: "ry", center: 0, housing: 0 },

                    { city: "yan", center: 0, housing: 0 },

                    { city: "tan", center: 0, housing: 0 },

                    { city: "itq", center: 0, housing: 0 },

                    { city: "abq", center: 0, housing: 0 }

                ]

            };         



        }

    ]);   

})();

Angular.html

<div class="row clearfix" ng-controller="app.views.automate as vm">

    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

        <div class="card">

            <div class="header">

                <h2>

                    Automate

                </h2>

            </div>

            <div class="body">





                <div id="wizard-step-container">

                    <ul class="nav nav-pills nav-justified">

                        <li ng-repeat="step in vm.steps" ng-class="{'active':step.step == vm.currentStep}"><a ng-click="vm.gotoStep(step.step)" href="">{{step.step}}. {{step.name}}</a></li>

                    </ul>

                </div>



                <div id="wizard-content-container">

                    <ng-include src="vm.getStepTemplate()"></ng-include>

                </div>



                <div id="wizard-navigation-container">

                    <div class="pull-right">

                        <span class="btn-group">

                            <button ng-disabled="vm.currentStep <= 1" class="btn btn-default" name="previous" type="button" ng-click="vm.gotoStep(vm.currentStep - 1)"><i class="fa fa-arrow-left"></i> Previous step</button>

                            <button ng-disabled="vm.currentStep >= vm.steps.length" class="btn btn-primary" name="next" type="button" ng-click="vm.gotoStep(vm.currentStep + 1)">Next step <i class="fa fa-arrow-right"></i></button>

                        </span>

                        <button ng-disabled="vm.currentStep != vm.steps.length" class="btn btn-success" name="next" type="button" ng-click="vm.save()"> <i class="fa fa-floppy-o"></i> Save</button>

                    </div>

                </div>

            </div>

        </div>

    </div>

</div>

Step1.html

<div class="step1">

    <div class="loading-icon" id="loading" ng-show="showLoader">

    </div>

    <div class="form-inline">

        <input type="file" class="form-control" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onchange="angular.element(this).scope().UploadFiles(this.files)" />

        <input type="button" value="Preview" class="btn btn-primary" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcel()" />

        <input type="button" value="Insert" style="margin-left: 15px;" class="btn btn-success" ng-show="IsVisible" ng-click="InsertData()" />

    </div>

    <br />



</div>

Excel.js

(function () {

    angular.module('app').controller('app.views.excel', [

        '$scope', 'abp.services.app.excel',

        function ($scope, ExcelService) {

            var vm = this;



            $scope.ParseExcel = function () {

                var formData = new FormData();

                var file = $scope.SelectedFileForUpload;

                formData.append('file', file);

                $scope.showLoader = true;   //show spinner

                var response = Excelservice.SendExcelData(formData);   //calling service

                response.then(function (d) {

                    var res = d.data;

                    $scope.BindData = res;

                    $scope.IsVisible = true; //showing the table after databinding

                    $scope.showLoader = false; //after success hide spinner

                }, function (err) {

                    console.log(err.data);

                    console.log("error in parse excel");

                });

            }



            $scope.InsertData = function () {

                var response = Excelservice.InsertToDB();

                response.then(function (d) {

                    var res = d.data;

                    if (res.toString().length > 0) {

                        $scope.Message = res + "  Records Inserted";

                        $scope.IsVisible = false;   //used to disable the insert button and table after submitting data

                        angular.forEach(

                            angular.element("input[type='file']"),

                            function (inputElem) {

                                angular.element(inputElem).val(null); //used to clear the file upload after submitting data

                            });

                        $scope.SelectedFileForUpload = null;   //used to disable the preview button after inserting data

                    }



                }, function (err) {

                    console.log(err.data);

                    console.log("error in insertdata");

                });

            }









        }

    ]);
    angular.module('app').service("Excelservice", function ($http) {

        this.SendExcelData = function (data) {

            var request = $http({

                method: "post",

                withCredentials: true,

                url: '/Home/ReadExcel',

                data: data,

                headers: {

                    'Content-Type': undefined

                },

                transformRequest: angular.identity

            });

            return request;

        }

        this.InsertToDB = function () {

            var request = $http({

                method: "get",

                url: '/Home/InsertExcelData',

                data: {},

                datatype: 'json'

            });

            return request;

        }

    });





    //used to check the extension of file while uploading

    function checkfile(sender) {

        var validExts = new Array(".xlsx", ".xls");

        var fileExt = sender.value;

        fileExt = fileExt.substring(fileExt.lastIndexOf('.'));

        if (validExts.indexOf(fileExt) < 0) {

            alert("Invalid file selected, valid files are of " +

                validExts.toString() + " types.");

            return false;

        }

        else return true;

    }







})();

错误详细信息

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

(function () {
    var controllerId = 'app.views.automate';
    angular.module('app').controller(controllerId, [
        '$scope','Excelservice', 'abp.services.app.automate', function ($scope, Excelservice, automateService) {
            var vm = this;
            // ...
        }]);
})();

https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3789#issuecomment-416031257