【问题标题】:passing angular service data to gaugechart controller将角度服务数据传递给仪表图控制器
【发布时间】:2015-07-29 16:09:36
【问题描述】:

我的项目中有一个仪表图控制器,它必须显示来自角度服务的数据。但是当我调用服务函数时它不会接受来自服务的数据。这是我正在尝试的:

 Controller.js

 angular.module("app.controllers", [])
 .controller("gaugeCtrl", ["$scope","config","myService",
  function ($scope,config,myService) {
    $scope.gaugeHome = {

      gaugeData: myService.getdata(),
      gaugeOptions: {
        lines: 12,
        angle: 0,
        lineWidth: 0.47,
        pointer: {
          length: 0.6,
          strokeWidth: 0.03,
          color: "#555555"
        },
        limitMax: "false",
        colorStart: config.secondary_color,
        colorStop: config.secondary_color,
        strokeColor: "#F5F5F5",
        generateGradient: !0,
        percentColors: [
          [0, config.secondary_color],
          [1, config.secondary_color]
        ]
      }
    }
  ])

这是我的服务数据。它确实获取数据但无法传递到控制器代码中的控制器 val 字段

  var demoService= angular.module('demoService',[])
  .service('myService',function($http,$q){
   var deferred = $q.defer();
  $http.get('http://enlytica.com/RSLivee/rest/census').then(function(data)
   {
     deferred.resolve(data);
 /*var v=0;
 $players=data.data;
    console.log($players.Tweets);
     ($players.Tweets).forEach(function(index, element) {
         v=v+ (index.FAVOURITE_COUNT);
         console.log(index.FAVOURITE_COUNT); 
     });
     console.log(v);
     deferred.resolve(v);*/
   });


this.getdata=function()
{  

var dataarr = [];
var v=0;
deferred.promise.then(function(data)
        {

    $players=data.data;
    console.log($players.Tweets);
     ($players.Tweets).forEach(function(index, element) {
         v=v+ (index.FAVOURITE_COUNT);
         console.log(index.FAVOURITE_COUNT); 
     });
     console.log(v); 
     dataarr.push({ maxValue: 3e3,animationSpeed: 100,val: v})
     console.log(dataarr);
    });

 return (dataarr);

 }
})

我也尝试在 controller.js 中获取数据,如下所示,但它也不起作用:

angular.module("app.controllers", []).controller("gaugeCtrl",["$scope","config","myService",
function ($scope,config,myService) {
var v=0;
var dataarr=[];
 var promise=myService.getdata();
console.log(promise);
var tp=promise.then(function(data)
        {
    $players=data.data;
    console.log($players.Tweets);
     ($players.Tweets).forEach(function(index, element) {
         v=v+ (index.FAVOURITE_COUNT);
        // console.log(index.FAVOURITE_COUNT); 
     });
     console.log(v);
     dataarr.push({ maxValue:800,animationSpeed: 100,val: v});
     console.log(dataarr);
     return dataarr;
    });
   ]}

dataarrv 值无法访问。有没有一种方法可以将值传递给我的仪表。

提前致谢

@OrenD 我更改了 Service.js 代码:[我删除了 DI,因为它抛出了一个错误 -->

  Error: [ng:areq] http://errors.angularjs.org/1.3.14/ng/areq?      
 p0=fn&p1=not%20aNaNunction%2C%20got%string
 at Error (native)
at http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:4847
at Sb (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:11576)
at tb (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:11670)
at Function.ab.$$annotate (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:16:25928)
at e (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:19914)
at Object.instantiate (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:20199)
at Object.<anonymous> (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:20480)
at Object.e [as invoke] (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:20075)
at Object.$get (http://localhost:8080/Enlytica18thOnwards/dist/js/app.js:14:19010) ]


 Service .js


 var demoService= angular.module('demoService',[])
 .service('myService', function($http, $q) {
  this.getData = function() {
   return $http.get('http://enlytica.com/RSLivee/rest/census')
    .then(function(data) {
      var v = 0;
      for (var i = 0; i < data.data.Tweets.length; ++i) {
        v += data.data.Tweets[i]['FAVOURITE_COUNT'];
      }
      console.log(v);//doesnt show anything on console
      return $q.when([{
        maxValue: 3e3,
        animationSpeed: 100,
        val: v
      }]);
    });
   };
  }
);

但是现在这不会从 url 读取数据。我做错了什么吗?

【问题讨论】:

    标签: jquery angularjs http service promise


    【解决方案1】:

    建议服务返回承诺,因为在很多情况下,请求的数据是从后端异步获取的。

    以下是服务的粗略实现,以提供可以在控制器中使用的承诺:

    app.service('myService', ['$http', '$q', function($http, $q) {
        this.getData = function() {
          return $http.get('http://enlytica.com/RSLivee/rest/census')
            .then(function(data) {
              var v = 0;
              for (var i = 0; i < data.data.Tweets.length; ++i) {
                v += data.data.Tweets[i]['FAVOURITE_COUNT'];
              }
              return $q.when([{
                maxValue: 3e3,
                animationSpeed: 100,
                val: v
              }]);
            });
        };
      }
    ]);

    现在,在控制器中,您必须根据提供的承诺的解决方案采取行动。你有几种选择:

    • 您可以使用对您的视图来说足够的数据来初始化 $scope.gaugeHome,直到从服务接收到实际数据,然后在解决承诺时设置 gaugeData 属性。
    • 您可以在该控制器的路由器配置的解析部分中添加对 myService.getData() 函数的调用。这样,您可以将已解析的 Promise 注入控制器并准备好数据,而无需从控制器内调用 getData() 函数。请注意,在此替代方案中,在从后端获取数据之前,不会准备/显示视图。

    这是一个代码 sn-p,显示了您可以使用已解决的 Promise 的数据更新 gaugeData 的方式:

    app.controller('gaugeCtrl', ['$scope', 'config', 'myService',
      function($scope, config, myService) {
        $scope.gaugeHome = {
          gaugeData: [],
          gaugeOptions: {
            lines: 12,
            angle: 0,
            lineWidth: 0.47,
            pointer: {
              length: 0.6,
              strokeWidth: 0.03,
              color: "#555555"
            },
            limitMax: "false",
            colorStart: config.secondary_color,
            colorStop: config.secondary_color,
            strokeColor: "#F5F5F5",
            generateGradient: !0,
            percentColors: [
              [0, config.secondary_color],
              [1, config.secondary_color]
            ]
          }
        }
    
        myService.getData().then(function(dataArr) {
          $scope.gaugeHome.gaugeData = dataArr;
        });
      }
    ]);

    【讨论】:

    • 感谢您的回复。但是,如果我将 return 与 $http 一起使用,该服务不会读取数据。我已经编辑了代码。我需要更改 app.js 中的任何内容吗?提前致谢
    • 似乎你定义了 2 个独立的 Angular 模块——一个用于服务(demoService),另一个用于控制器(app.controllers)。我认为这是根本原因。使用单个模块,看看它是否能解决问题。
    【解决方案2】:

    试试这个:-

        app.factory("companyData", function ($http) {
    return {
            getAll: function (items) {
                var path = "https://dl.dropboxusercontent.com/u/28961916/companies.json"
                $http.get(path).success(items);
            }
        }
    });
    letus consider this is a service
    here this returns items object
    if I want to use that items object in controller app.controller("mainController", function ($scope, companyData) {
        //console.log(companyData.getAll());
        companyData.getAll(function (companyDetails) {
            console.log(companyDetails)
        }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多