如何从角度服务到控制器获取数据?

时间:2016-10-31 19:24:08

标签: javascript angularjs

我有成功的服务器响应,我怎么能把它发送到控制器我尝试然后方法但它的抛出错误然后是nto定义,我怎么能实现这个任务?

service.js

angular.module('App').service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        console.log('service called', fd);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(resp){
        console.log('success',resp);
        return resp;
        })
        .error(function(){
        });
    }
}]);

controller.js

  $scope.uploadFile = function(){
                var file = $scope.myFile;
                // console.log('file is ');
                // console.dir(file);
                // console.log(file);
                var uploadUrl = "/fileUpload";
                fileUpload.uploadFileToUrl(file, uploadUrl).then(function(resp){console.log(resp);
};
            };

3 个答案:

答案 0 :(得分:1)

避免在服务中使用.success(无论如何已弃用),只返回承诺本身。

angular.module('App')

.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        // ... other code ...
        // return the $http promise itself here
        return $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
    }
}])

然后在你的控制器中(.catch是可选的,但如果你的$ promise出错,那么很好用。)

$scope.uploadFile = function(){
    // ... other code ...
    var uploadUrl = "/fileUpload";

    fileUpload.uploadFileToUrl(file, uploadUrl)
        .then(function(response) { console.log(response) })
        .catch(function(error) { console.log(error) });
};

答案 1 :(得分:0)

你必须返回Promise,然后才能在控制器中使用then

angular.module('App').service('fileUpload', ['$http', function ($http) {
 this.uploadFileToUrl = function(file, uploadUrl){
    var fd = new FormData();
    fd.append('file', file);
    console.log('service called', fd);
    return $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
 }
}]);

答案 2 :(得分:0)

像这样更改您的代码。

angular.module('App').service('fileUpload', ['$http', function ($http) {
  this.uploadFileToUrl = function(file, uploadUrl) {
    var fd = new FormData();
    fd.append('file', file);
    console.log('service called', fd);
    return $http.post(uploadUrl, fd, {
      transformRequest: angular.identity,
      headers: {'Content-Type': undefined}
    });
  }
}

$scope.uploadFile = function() {
  var file = $scope.myFile;
  // console.log('file is ');
  // console.dir(file);
  // console.log(file);
  var uploadUrl = "/fileUpload";
  fileUpload.uploadFileToUrl(file, uploadUrl)
    .then(function(resp) {
    console.log('Your response here', resp);
  });
};