javascript / angular - 无法获得确切的返回响应数据

时间:2016-03-03 02:02:11

标签: javascript html angularjs

美好的一天!

我刚刚注册了stackoverflow并提出了这个问题,因为我一直在通过搜索这个庞大而令人敬畏的网站来搜索这个问题。不幸的是,他们的问题和解决方案似乎对我没有帮助。

这是我的简短js代码:

angular.module('myapp', []).controller('myController', ['$scope', '$http', '$window', function($scope,$http,$window) {

...[more codes]...

$scope.callMeMaybe = function(coverImageId) {
  var THUMBNAIL_URL = './thumbnails/' + coverImageId;
  var THUMBNAIL_DATA_URI = new String('data:image/jpg; base64, ');
  var result = new String('');

  $http.get(THUMBNAIL_URL).then(function successCallback(response){
    var data = response.data;
    result = new String(THUMBNAIL_DATA_URI.concat(data));
    $scope.loaded = true;
  }, function errorCallback(response) {
    $scope.loaded = false;
    if ( response.status === 403 ) {
      $window.alert('You are forced logged out');
      $window.location = '/login/';
    } else {
      $scope.elementBindingError();
    }
  });
  console.log(result);
  return result.valueOf();
};

... [some more codes] ...
}])
.directive('myDirective', function(){
return {
  restrict: 'A',
  link: function(scope, element, attrs) {
    element.attr('src', scope.callMeMaybe(attrs.thumbnail));
  }
}
});

我似乎无法从callMeMaybe函数中获取连锁响应数据。 该指令是我< img>的一部分。标签

2 个答案:

答案 0 :(得分:0)

由于异步调用,可能会发生这种情况。在获取数据之前,callMeMaybe的返回正在发生。只有在调用successCallback / errorCallback时才应返回result。另外,请确保范围正确 - 如果没有HTML,则无法看到该部分。

答案 1 :(得分:0)

当你有一个ajax调用时,要注意你要返回的内容,如果它依赖于ajax成功结果那么你必须从成功回调本身返回结果,否则你怎么期望成功结果是在没有成功被召唤的情况下返回所以原型应该是下面的

        $scope.callMeMaybe = function (coverImageId,functionCompleteCallBack) { //pass a new function into this, with this function we will set the element src

        // ... your other stuff

        $http.get(THUMBNAIL_URL).then(function successCallback(response) {
            var data = response.data;
            result = new String(THUMBNAIL_DATA_URI.concat(data));
            $scope.loaded = true;

            functionCompleteCallBack(result.valueOf()); //You need to execute the function passed as a callback.

        }, function errorCallback(response) {
            $scope.loaded = false;
            if (response.status === 403) {
                $window.alert('You are forced logged out');
                $window.location = '/login/';
            } else {
                $scope.elementBindingError();
            }
        });           
    };

}])

           // ... your other stuff

.directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.callMeMaybe(attrs.thumbnail, function (elementSrc) { //note that we are passing a new function and set the element src inside this callback function
                element.attr('src', elementSrc);
            });
        }
    }
});

如果您有任何疑惑,请告诉我。