AngularJS:下载二进制映像时出现异步问题

时间:2013-12-05 15:29:59

标签: javascript angularjs asynchronous

我正在尝试使用$ http从我正在使用的服务中获取二进制图像,但我认为我遇到了异步问题。

以下是我在控制器中使用的代码:

$scope.downloadImage = function(imgReady, index) {
    if (imgReady == false) {

        for (var i = $scope.vehicles[index].events.length - 1; i >= 0; i--) {
            var config = {
                method: 'POST',
                url: '/Events/SnapShot',
                data: $scope.vehicles[index].events[i],
                cache: false
            }

            RequestService.makeApiRequest(config).success(function(response) {
                console.log(response.data); // shows the binary data
                $scope.vehicles[index].events[i].snapshot = response.data; // Results in: TypeError: Cannot set property 'snapshot' of undefined
            });

            console.log($scope.vehicles[index].events[i]); // Logs event object without snapshot property
        };
    }
}

以下是我视图中的代码:

<li ng-repeat="vehicle in vehicles" ng-init="isHidden=false; imgReady=false;" class="event-list-animation">
    <div ng-click="isHidden=!isHidden; downloadImage(imgReady, $index); imgReady=true" class="heading" ng-hide="vehicle.events.length < 1">
        <h1>Vehicle: {{ vehicle.name }}</h1>

        <span ng-class="(isHidden == false) ? 'details-toggle' : 'details-toggle open'">
            expand / collapse
        </span>
    </div>
    <div ng-show="isHidden" class="body event-show-hide-animation">
        <div class="wrap" ng-repeat="event in vehicle.events">
            <ul>
                <li>Event: {{ event.number }}</li>
            </ul>

            <img ng-src="{{ event.snapshot }}" />
        </div>
    </div>
</li>

所以我有几辆车,每辆车都有活动,我试图抓住每个事件的图像。但它似乎导致了异步问题。 我也试过了:

$scope.vehicles[index].events[i].snapshot = RequestService.makeApiRequest(config).success(function(response) {
    return response.data;
});

但是,这似乎会导致以下问题:GET http://localhost:3000/%7B%7D 404 (Not Found)

这是试图加载的二进制图像数据吗?这是我第一次使用二进制图像数据,并使用I have been told to use ng-src指令使其正确加载。

感谢您对此问题的任何帮助。

1 个答案:

答案 0 :(得分:1)

我认为TypeError因为您错误地捕获了函数闭包中的i

请试试这个:

RequestService.makeApiRequest(config).success(function(j) {
    return function(response) {
        console.log(response.data);
        $scope.vehicles[index].events[j].snapshot = response.data;
    }
}(i));