Search code examples
javascriptangularjsangularjs-service

Angularjs - Move service code to another file


I am having code like,

<script> 
var MyApp = angular.module("MyApp", ['mc.resizer','chart.js'])
MyApp.controller('Ctrl1', function ($scope, $http,MyService) {
        MyService.EnvDetails().then(function success(data){
            $scope.httpdata = data;
            }, function error(err){
                console.log("error found"); return err; 
            });
});
</script> 

And Trying to save service code in another javascript file in another folder which is like,

var MyApp = angular.module("MyApp", []);
MyApp.service('MyService', function($http) {
    this.EnvDetails = function() {
         return $http({
                    url: '/myurl'                    
        }).then(
            function successCallback(response) {
                //Some Code
                return //Some;
            }, function errorCallback(response) {                
                return response;
            }
        );
    };  
});

Saving this code in "MyService.js" and referring this file in as

<script type="text/javascript" src="javascripts/MyService.js"></script>

This is giving me error,

angular.js:11607 Error: [$injector:unpr] Unknown provider: getEnvDetailsServiceProvider <- getEnvDetailsService <- Ctrl1

But when i put Service code in same file (except the first line, var mainApp = angular.module("mainApp", []);) , along with controller code, it works. I am clueless, where i am missing the reference. Please help.

Thanks


Solution

  • When you are saving to another file, no need to add the modular declaration again,

    remove the dependencies

    //remove this line var MyApp = angular.module("MyApp", []);
    MyApp.service('MyService', function($http) {
        this.EnvDetails = function() {
             return $http({
                        url: '/myurl'                    
            }).then(
                function successCallback(response) {
                    //Some Code
                    return //Some;
                }, function errorCallback(response) {                
                    return response;
                }
            );
        };  
    });