【问题标题】:Call NodeJS Function in AngularJS在 AngularJS 中调用 NodeJS 函数
【发布时间】:2018-02-24 05:13:09
【问题描述】:
app.get("/myDBfunction",getCommunicationDetails);    
function myDBfunction(req,res){
     var queryObject = url.parse(req.url,true).query;
         console.log("req.method ",req.method);

    var resultset={};
        resultset.result=[];


     var queryString = `select * from table..`
     connection.query(queryString, function(err, result) {
                    if (!err){
                var response = [];
                response.push({'result' : 'success'});
                if (result.length != 0) {
                    response.push({'data' : result});
                } else {
                    response.push({'msg' : 'No Result Found'});
                }

                res.setHeader('Content-Type', 'application/json');
                res.status(200).send(JSON.stringify(response));
            } else {
                res.status(400).send(err);
            }
    })
        };

我创建了 Nodejs 函数用于连接到 mysql 并能够以 json 格式显示。 现在我想在 Angular js 中调用这个函数并将我的 json 转换为 excel 并下载报告。 我是 Angular 的新手,请帮助我完成全部步骤。 提前致谢。

编辑 1: Firstpro.html 文件

<html ng-app="myApp">

  <head>

    <script data-require="angular.js@*" data-semver="2.0.0" src="https://code.angularjs.org/1.4.8/angular.js"></script>
    <script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
  </head>

  <body ng-controller="MyCtrl">
  <script src="/app.js"></script>
    <h1>Export to Excel</h1>
    <button class="btn btn-link" ng-click="exportToExcel('#tableToExport')">
      <span class="glyphicon glyphicon-share"></span>
 Export to Excel
    </button>
    <div id="tableToExport">
      <table border="1">
        <thead>
          <tr class="table-header">
            <th>Team</th>
            <th>Process Type</th>
            <th>Cedent</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="data in details">
            <td>{{data.team}}</td>
            <td>{{data.type}}</td>
            <td>{{data.cedent}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>

</html>

myCtrl.js 文件

myApp.controller('myController',funtion($scope,$http){
   $http.get("/Details").then(function(response){ 
       $scope.details = response.data; //You get your data here from nodejs API, and iterate details in your View
     });
});

app.js 文件

var myApp=angular.module("myApp",[]);
myApp.factory('Excel',function($window){
        var uri='data:application/vnd.ms-excel;base64,',
            template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64=function(s){return $window.btoa(unescape(encodeURIComponent(s)));},
            format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];})};
        return {
            tableToExcel:function(tableId,worksheetName){
                var table=$(tableId),
                    ctx={worksheet:worksheetName,table:table.html()},
                    href=uri+base64(format(template,ctx));
                return href;
            }
        };
    })
    .controller('myCtrl',function(Excel,$timeout,$scope,$http){
      //get data from Node api; For example i will using $timeout just to simulate api call; Also i am assuming your JSON would be like below that i have assigned

      $timeout(function(){
        $scope.details = [
           { 
             team:'v1',
             type:'v2',
             cedent:'v3'
           },
           { 
             team:'v1',
             type:'v2',
             cedent:'v3'
           },
           { 
             team:'v1',
             type:'v2',
             cedent:'v3'
           }
        ]
      },1000)

      //below is how you would do your HTTP call tp node js server. I have commented this codefor now just to simulate the dummy data above in $timeout.
      /*$http.get("/myDBfunction").then(function(response){ 
       $scope.details = response.data; //You get your data here from nodejs API, and iterate details in your View
      });*/


      $scope.exportToExcel=function(tableId){ // ex: '#my-table'
            var exportHref=Excel.tableToExcel(tableId,'WireWorkbenchDataExport');
            $timeout(function(){location.href=exportHref;},100); // trigger download
        }
    });

现在我已经运行了 myHTML 文件,输出是这样的; 但它应该取自 MYsql 表。 导出到 Excel

Export to Excel
Team    Process Type    Cedent
{{data.team}}   {{data.type}}   {{data.cedent}}

【问题讨论】:

    标签: mysql angularjs json node.js excel


    【解决方案1】:

    EDIT2

    要从 SQL 中获取数据,请使用以下代码而不是 $timeout

    $http.get("/myDBfunction").then(function(response){ 
          console.log(response.data)
          $scope.details = response.data; // here you will get data
     },function(res){
          console.log("Error",res) //error occured
     });
    

    编辑

    您可以在控制器中调用 nodejs api,如下所示,并可以使用“ng-repeat”以表格格式显示 JSON 生成的视图

    在你的控制器中:

    myApp.controller('myController',funtion($scope,$http){
       $http.get("/myDBfunction").then(function(response){ 
           $scope.details = response.data; //You get your data here from nodejs API, and iterate details in your View
         });
    });
    

    并在视图中重复该数据

    <table>
       <tr ng-repeat="data in details track by $index" > // here I made changes
          <td> {{data.prop1}} //iterate over data here</td>
       </tr>
    </table>
    

    然后按照下面的编码导出到excel中

    // This will be your app.js file
    var myApp=angular.module("myApp",[]);
    myApp.factory('Excel',function($window){
            var uri='data:application/vnd.ms-excel;base64,',
                template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                base64=function(s){return $window.btoa(unescape(encodeURIComponent(s)));},
                format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];})};
            return {
                tableToExcel:function(tableId,worksheetName){
                    var table=$(tableId),
                        ctx={worksheet:worksheetName,table:table.html()},
                        href=uri+base64(format(template,ctx));
                    return href;
                }
            };
        })
        .controller('MyCtrl',function(Excel,$timeout,$scope,$http){
          //get data from Node api; For example i will using $timeout just to simulate api call; Also i am assuming your JSON would be like below that i have assigned
          
          $timeout(function(){
            $scope.details = [
               { 
                 team:'v1',
                 type:'v2',
                 cedent:'v3'
               },
               { 
                 team:'v1',
                 type:'v2',
                 cedent:'v3'
               },
               { 
                 team:'v1',
                 type:'v2',
                 cedent:'v3'
               }
            ]
          },1000)
          
          //below is how you would do your HTTP call tp node js server. I have commented this codefor now just to simulate the dummy data above in $timeout.
          /*$http.get("/myDBfunction").then(function(response){ 
           $scope.details = response.data; //You get your data here from nodejs API, and iterate details in your View
          });*/
        
        
          $scope.exportToExcel=function(tableId){ // ex: '#my-table'
                var exportHref=Excel.tableToExcel(tableId,'WireWorkbenchDataExport');
                $timeout(function(){location.href=exportHref;},100); // trigger download
            }
        });
    .table-header 
    {
    background-color: lightskyblue;  
    }
    <!-this is your HTML ->
    <html ng-app="myApp">
    
      <head>
        
        <script data-require="angular.js@*" data-semver="2.0.0" src="https://code.angularjs.org/1.4.8/angular.js
    "></script>
        <script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
      </head>
    
      <body ng-controller="MyCtrl">
        <h1>Export to Excel</h1>
        <button class="btn btn-link" ng-click="exportToExcel('#tableToExport')">
          <span class="glyphicon glyphicon-share"></span>
     Export to Excel
        </button>
            <button class="btn btn-link" ng-click="exportToExcel('#another')">
          <span class="glyphicon glyphicon-share"></span>
     Export to Excel Plain JSON
        </button>
        <div id="tableToExport">
          <table border="1">
            <thead>
              <tr class="table-header">
                <th>Team</th>
                <th>Process Type</th>
                <th>Cedent</th>
              </tr>
            </thead>
            <tbody>
              <tr ng-repeat="data in details track by $index">
                <td>{{data.team}}</td>
                <td>{{data.type}}</td>
                <td>{{data.cedent}}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div id="another">
          {{details}}
        </div>
      </body>
    
    </html>

    【讨论】:

    • 评论不适用于扩展讨论或调试会话;这个对话是moved to chat。如果您需要向问题添加信息,请对其进行编辑。其他相关信息应添加到答案中。
    • 如何使用当前时间戳更改导出的 Excel 工作表的名称?意味着 Excel 工作表名称应随时间一起提供。
    【解决方案2】:

    在 Angular 中你可以使用这种方式调用 api

    $http.get("/myDBfunction")
    .then(function(response){ $scope.details = response.data; });
    

    更多信息请查看this doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多