1

I am trying to insert new records into database by angularjs web application but problem is when i clicked the submit button i got following errors in console windows .I am trying to post the data from angularjs application throw wcf service .

 **TypeError: $http.post(...).success is not a function
        at Object.fac.UploadFile (Controllers.js:139)
        at Scope.$scope.SaveFile (Controllers.js:80)
        at fn (eval at compile (angular.js:15642), <anonymous>:4:144)
        at callback (angular.js:27463)
        at Scope.$eval (angular.js:18533)
        at Scope.$apply (angular.js:18632)
        at HTMLFormElement.<anonymous> (angular.js:27468)
        at defaultHandlerWrapper (angular.js:3785)
        at HTMLFormElement.eventHandler (angular.js:3773)**

Here is my controller.js code .

app.controller("AngularJs_WCFController", function ($scope, $timeout, $rootScope, $window, AngularJs_WCFService, FileUploadService) {
    $scope.date = new Date();
    //  To set and get the Item Details values 
    var firstbool = true;
    $scope.Imagename = "";
    $scope.Item_ID = "0";
    $scope.Item_Name = "";
    $scope.Description = "";
    $scope.Item_Price = "0";
    $scope.txtAddedBy = "";
    // This is publich method which will be called initially and load all the item Details.  
    GetItemDetails();
    //To Get All Records    
    function GetItemDetails() {
        var promiseGet = AngularJs_WCFService.GetItemDetails();
        promiseGet.then(function (pl) {
            $scope.getItemDetailsDisp = pl.data
        },
            function (errorPl) {
            });
    }

    //Declarationa and Function for Image Upload and Save Data 
    //-------------------------------------------- 
    // Variables 
    $scope.Message = "";
    $scope.FileInvalidMessage = "";
    $scope.SelectedFileForUpload = null;
    $scope.FileDescription_TR = "";
    $scope.IsFormSubmitted = false;
    $scope.IsFileValid = false;
    $scope.IsFormValid = false;
    //Form Validation 
    $scope.$watch("f1.$valid", function (isValid) {
        $scope.IsFormValid = isValid;
    });

    // THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular 
    // ------------------------------------------------------------------------------------ 
    //File Validation 
    $scope.ChechFileValid = function (file) {
        var isValid = false;
        if ($scope.SelectedFileForUpload != null) {
            if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {
                $scope.FileInvalidMessage = "";
                isValid = true;
            }
            else {
                $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";
            }
        }
        else {
            $scope.FileInvalidMessage = "Image required!";
        }
        $scope.IsFileValid = isValid;
    };
    //File Select event  
    $scope.selectFileforUpload = function (file) {

        var files = file[0];
        $scope.Imagename = files.name;
        alert($scope.Imagename);
        $scope.SelectedFileForUpload = file[0];

    }
    //---------------------------------------------------------------------------------------- 
    //Save File 
    $scope.SaveFile = function () {
        $scope.IsFormSubmitted = true;
        $scope.Message = "";
        $scope.ChechFileValid($scope.SelectedFileForUpload);
        if ($scope.IsFormValid && $scope.IsFileValid) {
            FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {

                var ItmDetails = {
                    Item_ID: $scope.Item_ID,
                    Item_Name: $scope.Item_Name,
                    Description: $scope.Description,
                    Item_Price: $scope.Item_Price,
                    Image_Name: $scope.Imagename,
                    AddedBy: $scope.txtAddedBy
                };

                var promisePost = AngularJs_WCFService.post(ItmDetails);
                promisePost.then(function (pl) {
                    alert(p1.data.Item_Name);
                    GetItemDetails();
                }, function (err) {
                    // alert("Data Insert Error " + err.Message); 
                });
                alert(d.Message + " Item Saved!");
                $scope.IsFormSubmitted = false;
                ClearForm();

            }, function (e) {
                alert(e);
            });
        }
        else {
            $scope.Message = "All the fields are required.";
        }
    };
    //Clear form  
    function ClearForm() {
        $scope.Imagename = "";
        $scope.Item_ID = "0";
        $scope.Item_Name = "";
        $scope.Description = "";
        $scope.Item_Price = "0";
        $scope.txtAddedBy = "";

        angular.forEach(angular.element("input[type='file']"), function (inputElem) {
            angular.element(inputElem).val(null);
        });
        $scope.f1.$setPristine();
        $scope.IsFormSubmitted = false;
    }
})
    .factory('FileUploadService', function ($http, $q) {

        var fac = {};
        fac.UploadFile = function (file) {
            var formData = new FormData();
            formData.append("file", file);
            var defer = $q.defer();
            $http.post("/shanuShopping/UploadFile", formData,
                {
                    withCredentials: true,
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity
                })
                .success(function (d) {
                    defer.resolve(d);
                })
                .error(function () {
                    defer.reject("File Upload Failed!");
                });
            return defer.promise;
        }
        return fac;


    }); 

here is the screen shot when i run the application..

enter image description here

  • In your uploadFile Function, instead of doing: `.success()` and `.error()`, try: `.then(successFunc, errorFunc)`. It sounds likes it doesnt recognize the success promise you created. When you look at what the properties are for an HttpPromise, you will see there is no success function as you defined. So i think `then` function may resolve your issue. Let me know, if my suspicion is correct. – Fallenreaper Jun 19 '18 at 00:55
  • Also avoid the use of the [defered Anti-pattern](https://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern). – georgeawg Jun 19 '18 at 04:09
  • 1
    See also [Why are angular $http success/error methods deprecated? Removed from v1.6?](https://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg Jun 19 '18 at 04:10

1 Answers1

1

Remove the deferred Anti-pattern from the factory:

app.factory('FileUploadService', function ($http, $q) {
    var fac = {};
    fac.UploadFile = function (file) {
        var formData = new FormData();
        formData.append("file", file);
        ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
        var promise = $http.post("/shanuShopping/UploadFile", formData,
            {
                withCredentials: true,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            })
            .then(function(response) {
                return response.data;
            })
            .catch(function(error) {
                console.log("File Upload Failed!");
                return $q.reject(error);
            });
            //.success(function (d) {
            //    defer.resolve(d);
            //})
            //.error(function () {
            //    defer.reject("File Upload Failed!");
            //});
        return  ̶d̶e̶f̶e̶r̶.̶p̶r̶o̶m̶i̶s̶e̶;̶  promise;
    }
    return fac;
}); 
georgeawg
  • 48,608
  • 13
  • 72
  • 95