Angular displaying undefined for service

I have created a service for uploading images to a server, and I am encountering an issue when calling this service from my controller. The error message indicates that the function 'uploadFileToUrl' is undefined.

Below is the code for my service:

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}
        })
        .then(function(response){
            console.log(response.data);
        }, function(error){
            console.error("Error occurred during file upload");
        });
    }
}]);

And here is how I am using this service in my controller:

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

    function studio(){
        var studioData = {"session_id": session_id, "u":[{"col":"studio","val":$scope.studioDetails.studio},{"col":"type","val":$scope.studioDetails.type}],"filter":[["id","=", "1"]], "table": "studio"};
        apiCall.callEndpoint(studioData,"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);
            }
        });

    }
});

An arrow has been added where the service is being called from.

Answer №1

There seems to be an issue with the injection

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

You've missed including fileUpload service in the parameter list

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

Answer №2

It is crucial to fulfill your duty, otherwise there will be no clear outcome

  function sendFileToServer($http) {

    var service = {};
    service.sendFileToServer = 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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...

Why isn't this code for hiding the animation and displaying it not functioning properly?

Why isn't this animation from display none to block working properly? The initial code appears as follows, and it functions correctly: $(".box_outer").stop().animate({top: '25px' , opacity: 1}, 100); When I add display: none; to the class ...

Experiencing a problem with the localhost connection

I've been trying to work on this issue using React and local host, but it keeps showing the direct file instead of the website. I've been stuck on this problem for the past 3-4 hours and still haven't been able to find a solution. I'm h ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

Adding Angular dependencies through Gulp (with the help of Browserify)

Exploring the use of Gulp and Browserify in my new Angular application. Inquiry: How can I effectively include angular dependencies in the app.js file without encountering dependency errors? Even with minimal dependencies, such as using only $stateProvid ...

The IDs and classes of HTML elements

I have two different implementations of a livechat script. On my sandbox site, the livechat is fixed to the bottom right of the page and scrolls with the window. However, on my live site (where this specific code comes from), it is attached to the footer. ...

How can I prevent users from selecting text when they right click using JavaScript?

My custom context menu on canvas works well, but I'm facing an issue with Text elements. When I try to right-click on a text element, it triggers text selection as if double-clicking. I attempted to use the following code: document.addEventListener(& ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

What is the best way to access a resource from an Angular.js module for a jasmine test?

My current project module includes resources and the code is structured as follows: editor_services.js var editorServices = angular.module('editorServices', ['ngResource']); editorServices.factory('Project', ['$resource ...

Retrieving information from the backend using JavaScript

Utilizing devexpress JS Charts requires data to be in the format: [{ category: 'Oceania', value: 35 },{ category: 'Europe', value: 728 }] To achieve this format, I convert a DataTable to JSON in my backend code after running queries b ...

Encountering issues with npm installation in AngularJS

I am new to angular js and just started learning it. However, I encountered an error when running the npm install command. npm install> [email protected] install C:\Users\A626262\WebstormProjects\FirstJsApp\node_modules\b ...

Utilize Jquery and MVC 5 to create a reoccurring partial view

I have a button that triggers the loading of a partial view containing a table with all the categories in my system. <input type="button" value="Load Categories" id="btnLoadCategories" /> This loading process is done via a partial view which is in ...

Ajax displays JSON data within an array format

Looking for a solution where I have MySQL data displayed in a table, with each row having a button. When the button is clicked, a bootstrap modal should appear containing that data. I have converted the MySQL data to JSON format and assigned the ".view_dat ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

Strategies for passing a JavaScript variable to a JSP function

I'm dealing with a JavaScript code that has a value stored in its variable that I need to pass to my JSP function. However, I'm facing trouble passing it along. Take a look at the following code snippets: Javascript: $('button').on(& ...

Is it possible to generate a component dynamically using a string template?

I have a Component called "CDataTable" that renders columns in a for loop. Inside the loop, there is a template: <template v-if="typeof col.template !== 'undefined'" #body="{data}"> <component :is="compile(co ...

Exploring the Reach and Sequence of AJAX Callbacks

This particular piece of code aims to achieve three main tasks: 1) validate the online status of users, 2) retrieve their information from a slightly different URL, and 3) present both sets of data in HTML format. The implementation appears functional bu ...

Customize the CloseIconButton in Material-UI Autocomplete for a unique touch

Hello everyone, I have a simple dilemma. I am trying to implement a custom closeIconButton, but the only available prop is closeIcon. However, this prop is not sufficient because I need this custom button to also have an onClick property. If I add the onC ...

The Vue.js component appears to be hidden within the Swal.fire HTML

Here is how I use Swal.Fire in my file1.js: import TextModuleComponent from "../components/TextModuleComponent"; export default { components: {TextModuleComponent} } Swal.fire({ title: 'Sending the offer via email?', ...

Will my JavaScript function be triggered when the page is resized while printing?

I have a simple HTML layout where I am using the TextFill jQuery library to automatically adjust the text size based on available space. Everything looks good on screen, but when printed, it seems like the page is resized and the JavaScript needs to be re ...