【问题标题】:d3Service in angular / ionic角度/离子中的 d3Service
【发布时间】:2015-08-14 10:45:14
【问题描述】:

我正在尝试使用工厂的角度使用 d3,但我不断收到错误

错误:未定义不是函数(评估 'd3Service.d3().then')

显然我一定做错了什么,但我无法发现它,这已经持续了好几天了! 也许你有提示? 提前致谢

d3.js

angular.module('d3', [])
    .factory('d3Service', [function(){
        return {
            d3: function(){
                return !function(){ d3 code here }();
            }
        }
]);

directives.js

angular.module('starter.directives', ['d3'])
    .directive('d3circle', ['d3Service', function(d3Service) {
        return {
            scope: {},
            link: function(scope, element, attrs) {
                d3Service.d3().then(function(d3){

                });
            }
        }
    }
]);

【问题讨论】:

  • 在 d3.js 文件中看到您将模块名称写为“d3”,在directive.js 文件中您将模块名称写为“starter.services”,请正确检查名称
  • @jarandaf 我按照 ng-newsletter 上的说明进行操作,但我无法弄清楚要在 angular.module('d3', []) .factory('d3Service', [function(){ var d3; // insert d3 code here return d3; }]; 插入什么代码是整个代码 !function(){}(); 还是只有括号内的代码?

标签: javascript angularjs d3.js ionic-framework ionic


【解决方案1】:

我认为您的问题是您试图在函数上使用 .then ,而 .then 用于承诺。

.then() 的正确使用方式

服务

.factory('Examples', function($http){   
getExampleData: function () {
           return $http.get('http://xxxxxx.com/api/Examples/GetExampleData')
      }
}) 

指令

.directive('d3circle', ['Examples', function(Examples) {
        return {
            scope: {},
            link: function(scope, element, attrs) {
                Examples.getExamplesData().then(function(data){
                // do something with data
                });
            }
        }
    }

为了解决你的问题,我认为你必须在你的服务中使用 $q 来解析你想要返回的代码。

像这个例子(来自 angularjs API)

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多