为控制器运行$ http的服务

时间:2015-06-22 14:08:19

标签: javascript angularjs

我有多个控制器需要使用我的自定义服务,使用$ http。我做了类似的事情

.service('getDB', function($http){
   return {
      fn: function(){

        return $http({
            url: "http://example.com",
            method: "GET"
        });

      }
   }
})

.controller('myCtrl', function($scope, getDB) {
console.log(getDB.fn());
}

在我的console.log的getDB.fn()中,我看到$ promise,如何获取响应数据?

1 个答案:

答案 0 :(得分:2)

$ http返回一个承诺。它的实现可以在这里理解: $q

为了使用您的承诺,您必须执行以下操作:

.controller('myCtrl', function($scope, getDB) {
    getDB.fn(something).then(function(result){
         // The result can be accessed here
    }, function(error){
         //If an error happened, you can handle it here
    });
}

这是您传递参数的方式:

.service('getDB', function($http){
 return {
   fn: function(something){

    return $http({
        url: "http://example.com/" + something,
        method: "GET"
    });

   }
 }
})