Angular - 从工厂接收$ http响应时遇到麻烦

时间:2016-12-27 19:24:46

标签: angularjs angular-http angular-factory

我有一个angular factory与服务器进行一些$http通信并返回一个字符串。但是我收到Cannot read property 'then' of undefined错误。我看了herehere但遇到类似的问题,但我无法解决问题。

这是服务代码:

factory("availabilityService", ['$http', function ($http) {

    return {
        checkAvailability1: function (element, string) {
           // ..... some object creation code ......
            $http({
                method: 'POST',
                url: 'server/server.php',
                data: AvailableObj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
                .then(function successCallback(response) {
                    return response;

                }, function errorCallback(response) {
                });
        }
    }
}]);

controller内:

$scope.checkAvailability = function (element, string) {
   availabilityService.checkAvailability1(element, string).then(function (response) { //on this line the error occurs 
       console.log(response);

   });

1 个答案:

答案 0 :(得分:2)

您需要返回/usr/bin/cpp-4.7 -C -P myfile.F90 > myfile.f90 返回的承诺,即添加'返回'在$ http前面让你的代码如下所示:

$http

这是因为,你从控制器调用的函数应该有一个return $http(...) .then(function successCallback(response) { return response; }, function errorCallback(response) { }); 方法,即它应该是一个promise。 angular中的.then返回一个promise,它需要在工厂中由函数checkAvailability1返回。您只是从成功回调中返回响应,这是您的方法在控制器中不期望的。

相关问题