服务显示角度未定义

时间:2017-10-10 07:58:51

标签: javascript angularjs angular-services

我已经编写了一个服务,它将上传图像到服务器,我正在使用来自控制器的服务,但是在服务中调用显示在服务中定义的未定义函数。和错误是这样的"无法读取属性' uploadFileToUrl'未定义"

这是我的代码

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

在这里我称这项服务为

app.controller('settingsCtrl', ['$scope','apiCall','$filter', function($scope,apiCall,$filter,fileUpload){
    $scope.saveStudioBranch = function(){
        studio();
        admin();
        branch();
    }

    function studio(){
        var studio_json = {"session_id":session_id,"u":[{"col":"studio","val":$scope.studioDetails.studio},{"col":"type","val":$scope.studioDetails.type}],"filter":[["id","=","1"]],"table":"studio"};
        apiCall.callEndpoint(studio_json,"settingRoute.php","update",json_header).then(function(response){
            if(response.data.error == 0){
                if($scope.inst_logo != undefined ){
                    var uploadUrl = "https://papa.fit/routes/registrationRoute.php?action=instLogo";
                    -->> fileUpload.uploadFileToUrl($scope.inst_logo,session.client_id,uploadUrl);
                }
            }
            else
                show_snack(response.data.message);
        });

    }
});

我添加了一个箭头,我从

呼叫服务

2 个答案:

答案 0 :(得分:4)

错误在注射中

app.controller('settingsCtrl', ['$scope','apiCall','$filter', 
  function($scope, apiCall, $filter, fileUpload){

您忘记在参数列表中添加fileUpload服务

app.controller('settingsCtrl', ['$scope','apiCall','$filter', 'fileUpload',
  function($scope, apiCall, $filter, fileUpload){

答案 1 :(得分:0)

您必须返回您的服务,否则它将是未定义的

  function uploadFileToUrlSrv($http) {

    var service = {};
    service.uploadFileToUrl = function(file,clientid, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        fd.append('id', clientid);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(response){
            console.log(response)
        })
        .error(function(){
        });
    }
    return service;
}