0

I am trying to add a service to eliminate some code that I have been repeating through my app.

The service:

    /* --------------------------------------------------------------
---------- FUNCTIONS FOR PAGE ALERTS THROUGHOUT Project-------
---------------------------------------------------------------*/
angular.module('app').service('PageAlertService', function () {

    this.setAlert = function() {
        console.log("In setAlert");
        if (localStorage.getItem("Success")) {
            var alertObj = {
                alert: "Success",
                alertMessage: localStorage.getItem("Success")
            };
        } else if (localStorage.getItem("Error"){
            var alertObj = {
                alert: "Error",
                alertMessage: localStorage.getItem("Error")
            };

        };
        return alertObj;
    };

    this.errorStatusCheck = function(error, successString) {
        if (error.status = -1) {
            localStorage.setItem("Success", successString);
        } else {
            localStorage.setItem("Error", "Error occured: " + error.status + error.statusText);
        };
    };

});

but whenever I try to add it to any of my controllers I'd like to use it in it breaks my angular web app and gives me the

Error: $injector:unpr
Unknown Provider

Here is my app.js:

var app = angular.module('app',
    [
        'JobCtrl',
        'JobSvc',
        'WebsiteCtrl',
        'WebsiteSvc',
        'myClientCtrl',
        'ClientSvc',
        'MediaCompanyCtrl',
        'MediaCompanySvc',
        'PageAlertSvc',
        'ui.bootstrap',
        'ui.bootstrap.tpls'
    ]
);

Here is my controller:

/* --------------------------------------------------
-------- Media Jobs Controller ----------------------
--------------------------------------------------- */
angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.controller('JobCtrl',
        [
            'JobService',
            'WebsiteService',
            'MediaCompanyService',
            'ProductService',
            '$scope',
            '$uibModal',
            'PageAlertService',
            function (JobService, WebsiteService, MediaCompanyService,
                ProductService, $scope, $uibModal, $uibModalInstance, PageAlertService)
{
    /* ------------------------------------
    ---------  Variables  -----------------
    -------------------------------------*/
    $scope.mediaCompanies = {};
    $scope.websites = {};
    $scope.products = [];
    $scope.selectedProducts = [];
    $scope.isSelected = false;
    $scope.new = {
        Job: {}
    };

    /* ----------------------------------------------------------------
    --- INITIALIZE LISTS OF JOBS, WEBSITES, COMPANIES, AND PRODUCTS ---
    ------------------------------------------------------------------*/

    /* Get Jobs Initialization */
    function getJobs() {
        JobService.getJobs()
            .then(
            function (data) {
                $scope.total_count = data.JobCount;
                $scope.model = data.mediaJobList;

            },
            function (errResponse) {
                console.log("Error while getting jobs");
            });
    };
    getJobs();

    /* Get Websites Initialization */
    function getWebsites() {
        WebsiteService.getWebsites()
            .then(
            function (data) {

                $scope.websites = data;

            },
            function (errResponse) {
                console.log(errResponse);
            });
    };
    getWebsites();

    /* Get Companies Initialization */
    $scope.getCompanies = function () {
        MediaCompanyService.getCompanies()
            .then(
            function (data) {
                $scope.mediaCompanies = data;

            },
            function (errResponse) {
                console.log(errResponse);
            });
    };
    $scope.getCompanies();


    /* Get Products -- passing website id*/
    $scope.getProducts = function (webid) {
        ProductService.getProducts(webid)
        .then(
        function (data) {
           $scope.selectedProducts = data.MediaProductList;
        },
        function (errResponse) {
            console.log(errResponse);
        });
    };

      /* ----------------------------------------------------------------
      ----------- STILL NEED TO FIGURE OUT WHAT TO DO WITH YOU ----------
      ------------------------------------------------------------------*/
    ///* Shows Success and Error Alerts - Maybe make into a directive or 
    //    Service?                                                    */
    //if (localStorage.getItem("Success")) {
    //    $scope.alert = "Success";
    //    $scope.alertMessage = localStorage.getItem("Success");
    //    localStorage.clear();
    //} else if (localStorage.getItem("Error") && localStorage.getItem("Error") !== null) {
    //    //sometimes get errors even when adding, deleting, updating is successful
    //    $scope.alert = "Error";
    //    $scope.alertMessage = localStorage.getItem("Error");
    //    localStorage.clear();
                //};

    if (localStorage.getItem("Success") != null || localStorage.getItem("Error") != null) {
        console.log("I'm In")
        var alert = {};
        alert = PageAlertService.setAlert();
        //$scope.alert = alert.alert;
        //$scope.alertMessage = alert.alertMessage;
        localStorage.clear();
    }



    /* -----------------------------------
    ------  JOB CRUD FUNCTIONS ----------
    -------------------------------------*/

    /* Add Job - Also Adds Products to Database */
    $scope.addJob = function () {
        var successString = "Added Job Succesfully!";
        JobService.addJob($scope.new.Job).then(
            function (success) {
                localStorage.setItem("Success", successString);
            },
            function (error) {
                //if (error.status = -1 && error.status !== 500) {
                //    localStorage.setItem("Success", successString);
                //} else {
                //    localStorage.setItem("Error", "Error while adding Job! " + error.status + ":" + error.statusText);
                //}
                PageAlertService.errorStatusCheck(error, successString);
            });

        //adds products after adding job
        addProducts();

        location.reload();
    }

    /* Update Job -- Also Updates Products in Database */
    $scope.updateJob = function (job) {
        var successString = "Updated Job Succesfully!";
        JobService.updateJob(job).then(
            function (success) {
                localStorage.setItem("Success", successString);
            },
            function (error) {
                //if (error.status = -1 && error.status !== 500) {
                //    localStorage.setItem("Success", successString);
                //} else {
                //    localStorage.setItem("Error", "Error while updating job! " + error.status + ":" + error.statusText);
                //}
                PageAlertService.errorStatusCheck(error, successString);
            }
        );
        updateProducts();
        location.reload();
    }

    /* Delete Job */
    $scope.deleteJob = function (job) {
        var successString = "Deleted Job Succesfully!";
        var indx = $scope.model.indexOf(job);
        JobService.deleteJob(job.Id).then(
            function (success) {
                localStorage.setItem("Success", successString);
            },
            function (error) {
                //if (error.status = -1 && error.status !== 500) {
                //    localStorage.setItem("Success", successString);
                //} else {
                //    localStorage.setItem("Error", "Error occured while deleting job! " + error.status + ":" + error.statusText);
                //}
                PageAlertService.errorStatusCheck(error, successString);
            }
        );
        location.reload();
    }

    /* Run Job */
    $scope.runJob = function (id, d1, d2) {
        $scope.runButtonText = "Running";
        //format Date
        var date1 = $scope.FormatDate(d1);
        var date2 = $scope.FormatDate(d2);
        JobService.runJob(id, date1, date2).then(
            function (success) {
                $scope.runButtonText = "Finished";
            },
            function (error) {
                if (error.status = -1 && error.status !== 500) {
                    $scope.runButtonText = "Finished";
                } else {
                    $scope.runButtonText = "Error Occured";
                    console.log(error);
                }
            });
    }

    /* ----------------------------------------------------
    ---------- PRODUCT CRUD FUNCTIONS ---------------------
    ------------------------------------------------------*/
    var addProducts = function () {
        ProductService.addOrUpdate($scope.products).then(
            function (response) {
                console.log(response);
            },
            function (err) {
                console.log(err);
            });
    };

    var updateProducts = function () {
        ProductService.addOrUpdate($scope.selectedProducts).then(
            function (response) {
                console.log(response);
            },
            function (err) {
                console.log(err);
            });
    };

    var deleteProducts = function (product) {
        ProductService.deleteProduct(id).then(
            function (response) {
                console.log(response);
            },
            function (err) {
                console.log(err);
            });
    };

    /* ----------------------------------------------
     --------- Code to Manipulate View Model --------
     ----------------------------------------------*/

    /* Toggles Active Toggle Button */
    $scope.updateActive = function (job) {
        job.Active = !job.Active;
        setTimeout(function () {

        }, 500);
        this.updateJob(job);
    }

    /* Selects Job and and Gets Product List */
    $scope.selectJob = function (job) {
        $scope.isSelected = true;
        $scope.goToJobSection = false;
        $scope.goToEditSection = true;
        $scope.selectedJob = {} 
        $scope.selectedJob = job;

        //selects product list by webid
        var websiteId = $scope.selectedJob.WebsiteId;
        $scope.getProducts(websiteId);
    }

    /* Onclick Event to stop people from 
     adding products to database with different 
     website ids*/
    $scope.remProdOnClick = function () {
        var newList = [];
        if ($scope.goToEditSection == false) {
            $scope.products = [];

        }
    }

    /* ----------------------------------------------------------
    --- MODAL -- May need to bring this out into a Directive ----
    -----------------------------------------------------------*/
    /* Shows Modal */
    $scope.showModal = function (action, obj) {
        $scope.$modalInstance = $uibModal.open({
            scope: $scope,
            inputs: {
                title: action + " Job"
            },
            restrict: "E",
            templateUrl: 'app/modal/JobModals/modal' + action + 'Template.html',
            controller: "JobCtrl",
            backdrop: 'static',
            keyboard: false
        });
    }

    /* Exits Modal */
    $scope.exitModal = function () {
        $scope.$modalInstance.dismiss('cancel');
    };
}]);

I cannot seem to figure out why this is occurring. All my other services are working perfectly.

Thanks!

3 Answers 3

2

On your controller declaration, you inject 7 dependencies, but you have 8 as arguments, you are either forgetting to inject one dependency or to delete one argument.

angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.controller('JobCtrl',
        [
            'JobService',
            'WebsiteService',
            'MediaCompanyService',
            'ProductService',
            '$scope',
             // missing dependency here
            '$uibModal',
            'PageAlertService',
            function (JobService, WebsiteService, MediaCompanyService,
                ProductService, $scope, $uibModal, 
                $uibModalInstance // or extra dependency here
                , PageAlertService)
{
...
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the answer, sadly this did not solve my issue. I removed $uibModalInstance, seeing as I did not need it in the first place, and added my PageAlertService in the correct places ( the bottom of the dependencies and bottom of the arguments. I am still getting the same error as before.
@DDelgro Does the service declaration run before the controller? It is possible that you are trying to inject a service that was not created yet
How would I know if it did? @Bruno Santos
I have figured out a way to get my app to run with my service but it does not make any sense to me. I removed the PageAlertSvc.js file from it's Common Folder within my App folder and put it into the folder with all my other services. Why will angular not recognize a new folder within it's own app folder?
I can't tell for sure, but probably somewhere in your project (on one import, or project configuration) you are pointing to that folder. As I said, you were getting that error because the service was not declared when you tried to inject it in the controller. Try to find where you have that reference to that folder, but I'm glad you got it working!
|
1

I tried multiple solutions but the only thing that seemed to work was by putting my service into the folder with all my other services. Once it was moved I no longer got the $injector error I was talking about above.

/MainProject
   -/app
      -/Common
      -/Controllers
         JobCtrl.js
         OtherCtrl.js
      -/Services
          JobSvc.js
          PageAlertSvc.js
          OtherSvs.js
      -/Modal
      -/Templates
      -/Vendor
      app.js

As you can see instead of putting the PageAlertSvc.js in Common I had to put it in the Services folder.

3 Comments

Although I figured out a solution, I would really like for someone to help or explain to me how i can use the Common Folder as the place for this type of code to live. I have looked all over my project to find a place where I could be specifically pointing to the Services folder for my solution above to work, but found nothing to prove that fact! Any help would be appreciated :)
Glad you got it figured it out. I am not aware of any restriction around directory names. Have you confirmed that all your scripts are being imported in the correct order in your index.html?
I am honestly not sure. Reason being, this is an Asp.net and AngularJS web app. So I believe all my .js files are in the BundleConfig.cs stated as "bundles.Add(new ScriptBundle("~/bundles/Angular").IncludeDirectory("~/app","*.js",true));
0

In your controller, you should not need to redefine your module (with its associated dependencies) since it is already defined by app.js. Perhaps try attaching your controller to the existing module.

angular
    .module('app')
    .controller('JobCtrl', ...

Speaking of app.js, you should not need to inject any of your components/controllers/services since they will be programatically attached later.

angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls']);

1 Comment

If I remove ui.bootstrap and or ui.bootstrap.tpls I get another injection error. So I believe they are needed and must be called within my controller. I have tried not listing any dependencies, but I believe this is a path issue that I do not understand enough. I will post my solution to my issue since I have figured out a way to get it to work. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.