2016-07-23 26 views
0

實際上,我使用服務上傳圖片,圖片上傳成功,但是我想要響應數據到控制器中的函數。Angular Service Function如何向控制器返回響應

控制器:

adminApp.controller('imageController', ['$scope', 'fileUpload', 'Images',function ($scope, fileUpload, Images) { 

$scope.uploadFile = function (data) { 
    console.log(data); 

    var file = data.myFile; 
    console.log('file is '); 
    console.dir(file); 
    var uploadUrl = "/image"; 
    fileUpload.uploadFileToUrl(file, data, uploadUrl); 
    // $scope.images.push(); 

    }; 
}]); 

服務:

adminApp.service('fileUpload', ['$http', function ($http) { 

this.uploadFileToUrl = function (file, data, uploadUrl) { 
    var fd = new FormData(); 
    fd.append('file', file); 
    fd.append('owner_id', data.owner_id); 
    $http.post(uploadUrl, fd, { 
      transformRequest: angular.identity, 
      headers: {'Content-Type': undefined} 
     }) 
     .success(function (data) { 
      // return data; 
     }) 
     .error(function() { 
     }); 
    } 
}]); 

laravel(反手):

public function store(Request $request) 
{ 
    $image = $request->file('file'); 
    $image = $this->imageRepository->makeImage($image); 
    return $image; 
} 

我在服務返回功能從反手響應數據提供給控制器,所以可推控制器功能中的值爲$scope.images

回答

1

您可以在這裏利用角度$q

更新服務功能

this.uploadFileToUrl = function (file, data, uploadUrl) { 
    var defer = $q.defer(); 

    var fd = new FormData(); 
    fd.append('file', file); 
    fd.append('owner_id', data.owner_id); 
    $http.post(uploadUrl, fd, { 
      transformRequest: angular.identity, 
      headers: {'Content-Type': undefined} 
     }) 
     .success(function (data) { 
      // return data; 
      defer.resolve(data); 
     }) 
     .error(function (error) { 
      defer.reject(error); 
     }); 
    } 

return defer.promise; 

}]); 

在你的控制器,你可以使用函數作爲

fileUpload.uploadFileToUrl(file, data, uploadUrl).then(function(response){ 

    //response contains your data form service 

}).catch(function(error){ 

    // error variable contains error data from service. 

}); 

的代碼沒有經過測試..但它應該工作或非常接近。

+0

顯示錯誤,angular.min.js:92 TypeError:無法讀取未定義的屬性'defer' –

+1

在您的服務中,您需要包含延遲'adminApp.service('fileUpload',['$ http','$ q',函數($ http,$ q)' –

+0

包括然後顯示,** TypeError:無法讀取屬性'延期'的undefined ** –

相關問題