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

Error occurred while fetching image from Medium story API in Next.js

While working on my Next.js app, I encountered an issue with the Medium story API. Every time I try to fetch and display an image using the API, I receive an error message stating "upstream image response failed." The specific error code is: upstream image ...

Is it possible to call a function directly from useEffect?

Code VersionA: useEffect(() => doRequest(), []); Code VersionB: useEffect(() => { doRequest(); }, []); I used to believe that both versions were the same, with VersionA being a shortcut and VersionB allowing for multiple commands within the inlin ...

Custom Select Menu Options from Basic Key-Value Mapping

There are other answers that discuss using ng-option with an object structure like this: $scope.opts = [ {value: 111, text: '1st' }, {value: 222, text: '2nd' } ]; However, I am curious if it is possible to achieve the same functi ...

Tips for saving an array from the server into a script variable

I'm currently working with the express js framework along with Handlebarsjs as the templating engine. My aim is to pass an array from the router to the view, and then store this array within a script tag. //users is an array res.render('chatRoom ...

Error message: The AJAX POST request using jQuery did not return the expected data, as the data variable could not be

There is a script in place that retrieves the input text field from a div container named protectivepanel. An ajax post call is made to check this text field in the backend. If the correct password is entered, another div container panel is revealed. < ...

Is there a way to create a PHP function that can process an AJAX request and return a boolean value?

After some testing, I discovered that when the code snippet below is executed within my PHP function to manage an AJAX call: session_start(); if ( $_POST['animal'] != $_SESSION['animal'] ) die(json_encode(false)); Upon returning to th ...

What is the most effective method for integrating additional CSS/JS libraries into a GitHub repository?

I would like to integrate FontAwesome, Bulma, jquery, and jquery-ui into one of my Github repositories for the front-end section. Currently, I am including the JS files or CSS files from these projects in my own JS/CSS folders, but I believe there might ...

AngularJS Resource does not support array as input

I am struggling with AngularJS to fetch a JSON array (a list of strings). I have set up a Resource for this purpose as shown below: packageResource.factory('Package', ['$resource', function($resource) { return $resource('/stat ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

What is the best way to structure files within the css and js folders after running the build command in Vue-cli?

Vue-cli typically generates files in the following structure: - dist -- demo.html -- style.css -- file.commom.js -- file.commom.js.map -- file.umd.js -- file.umd.js.map -- file.umd.min.js -- file.umd.min.js.map However, I prefer to organize them this way: ...

References to high order functions in JavaScript

Although the code below is functional, I believe there might be a more efficient approach. I am currently passing a reference to the higher-order function's scope. var self=this; this.nodeModal.find(".modal-footer .save").click(function(){ ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

Comparing dates in JavaScript using the built-in Date object

Currently, I am attempting to compare the current date with the one stored in a database using the code snippet below: <script> $("#registerButton").click(function() { var first = $("#scantime").val(); var second = $("#scanbartime").val(); if (parse ...

Angular single page application with a sleek, user-friendly navigation bar for easy browsing

I have been attempting to solve the issue at hand without much success. As a newcomer to web development, I have been working on creating a basic app using angularjs and bootstrap. My pages are fairly sparse, consisting only of a few inputs and buttons t ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

Tips for circumventing the ajax data size restriction in asp.net mvc3

Currently, I am implementing an auto suggest function using AJAX in the following manner: $("#empName2").autocomplete({ search: function (event, ui) { var key = CheckBrowser(event); if (key == 13) return tr ...

Show pictures in AngularJS Modal with ng-repeat loop

Here is the index.html document: <!DOCTYPE html> <html ng-app="myApp" ng-app lang="en"> <head> <meta charset="utf-8"> <link href="css/bootstrap.min.css" rel="stylesheet"> <style type="text/css"> ul>li ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

What could be the reason for the selection box in my form not changing the items when togg

I'm having an issue with my form selection box code that used to work but is now not functioning properly. Could someone please help me identify where the error lies? Essentially, I have a form with the ID #main and a select box named #chart-type. Th ...

Having difficulties creating an array due to identical id tags causing HTML to break in JavaScript

I've been grappling with this issue all day. Before delving into dynamic solutions, I'd like to create multiple divs with unique id tags or classnames rather than repeating ids. Whichever option proves simpler would be greatly appreciated. Curren ...