Angular 'Unknown provider error' (of a factory file) when I use ngroute

405 views Asked by At

I want to pick this html page:

<h2 class="sub-header" style="color:#4e67c3;">Elenco dipendenti</h2>
          <div class="table-responsive">
            <table id="thetable">
                
             
                <tr> 
                    <th class="th2">Nome</th>  
                    <th class="th2">Cognome</th>  
                    <th class="th2">Data di Nascita</th>   
                    <th class="th2">Telefono</th>  
                    <th class="th2">&nbsp;&nbsp;Sesso&nbsp;&nbsp;</th> 
                    <th class="th2">&nbsp;StaffId&nbsp;</th>
                    <th class="th2">Email</th> 
             </tr> 
             
              
              <tr ng-repeat="staff in staffs">  
                 
           <td> {{ a }}</td> 
            <td> {{ staff.name }}</td>  
            <td> {{ staff.surname }}</td>    
            <td> {{ staff.birthDate }}</td>
            <td> {{ staff.phone }}</td> 
            
   
            <td>
                <div ng-switch on="staff.gender">
                <span ng-switch-when="true">Uomo</span>
                <span ng-switch-when="false">Donna</span>
                </div>
            </td>
                    
            
            <td> {{ staff.idstaff }}</td>  
            <td> {{ staff.staffLogin.email }}</td> 
    

            </tr>  
          
            </table>

      <script src="./scripts/bootstrap.min.js.download"></script>
    <script src="./scripts/docs.min.js.download"></script>
               
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script> 
 <!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.js"></script> -->

             
      <script src="scripts/rest-services.js"></script>
    <script src="scripts/jquery.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <script src="scripts/angular.js"></script>
  <!--  <script src="scripts/emailchecker.js"></script>  --> 
    <script src="scripts/angular-bootstrap-datepicker.js" charset="utf-8"></script>
   <!-- <script src="scripts/number-directive.js"></script> -->
    <script type="application/javascript"></script>

In this page, when I click one button:

<!DOCTYPE html>
<!-- saved from url=(0069)https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="shortcut icon" href="images/puzzle.png" />
      
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<!--    <link rel="stylesheet" href="styles/angular-bootstrap-datepicker.css" /> --> <!-- penso di poterlo togliere -->
    <link rel="stylesheet" href="styles/mainBoot.css">
    <link rel="stylesheet" href="styles/scrollbar.css">
    <link rel="stylesheet" href="styles/noscroll_numberfield.css">
    
 
 

  <!--  <script src="scripts/emailchecker.js"></script>  --> 
 
 <!--   <script src="scripts/angular-bootstrap-datepicker.js" charset="utf-8"></script> -->
   <!-- <script src="scripts/number-directive.js"></script> -->
    <script type="application/javascript"></script>
    
    <title>Pannello Amministratore</title>

    <!-- Bootstrap core CSS -->
    <link href="./styles/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="./styles/dashboard.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy this line! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  <style id="holderjs-style" type="text/css"></style></head>

  <body ng-app="StaffManagement" background="images/sfondoblu3.png">

    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand">FDDispenser</a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="fixed_admin.html#/">Pannello Amministratore</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/#">Settings</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/#">Profile</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/#">Help</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>
        </div>
      </div>
    </div>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
           <li class="active"><a  href="#/showemp">Mostra Dipendenti</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/#">Mostra Catalogo</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/#">Mostra Macchinette</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/#">Mostra Acquisti</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li class="active"><a href="edit_employee.html">Aggiungi/Modifica Dipendente</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Crea/Modifica Catalogo</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Famiglia</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Categoria</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Produttore</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Ingrediente</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Fabbrica di produzione</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Macchinetta</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Tipologia Macchinetta</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Aggiungi/Modifica Accessori</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Assegna Macchinetta a Dipendente</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Posiziona Macchinetta sul Territorio</a></li>
            <li><a href="https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/">Assegna Prodotti a Macchinetta</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
            
          <div ng-view></div>
            
            
        </div>
      </div>
    </div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
  <!--  <script src="./Dashboard Template for Bootstrap_files/jquery.min.js.download"></script> -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script> 
 <!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.js"></script> -->

      

    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
    <script src="scripts/main-admin.js"></script>

    <script src="scripts/jquery.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
      
    <script src="./scripts/bootstrap.min.js.download"></script>
    <script src="./scripts/docs.min.js.download"></script>
        

</body></html>

the ngroute function is in this js file called "main-admin.js":

var app = angular.module("StaffManagement", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "home_admin.html"
    })
    .when("/showemp", {
        templateUrl : "provaEmp.html",
        controller: "StaffController"
    })
    .when("/paris", {
        templateUrl : "paris.htm"
    });
});


app.controller("StaffController", function($scope, $filter, $http, restService) {  
                

                
    $scope.name = "ciao";
    restService.allstaffworking(_getstaff, _error);
     function _getstaff(response){
                    if (response.data == ""){
                        console.log("Accesso non autorizzato")
                    }
                    $scope.staffs = response.data;  
                }
           
                function _success(response) {  
                   // console.log(staff.name);
                    console.log("successo");
                    
                    _refreshStaffData();  
                    _clearFormData();
                    _showSB();
                    console.log("cleared");
                
                }  
           
             
      }); 

When I click on the button "Mostra Dipendenti", from main-admin.js the application show me "provaEmpl.html":

<h2 class="sub-header" style="color:#4e67c3;">Elensco dipendenti</h2>
          <div class="table-responsive">
            <table id="thetable">
                
             
                <tr> 
                    <th class="th2">Nome</th>  
                    <th class="th2">Cognome</th>  
              
                    <th class="th2">Telefono</th>  
                    <th class="th2">&nbsp;&nbsp;Sesso&nbsp;&nbsp;</th> 
                    <th class="th2">&nbsp;StaffId&nbsp;</th>
                    <th class="th2">Email</th> 
             </tr> 
             
              
                
                 

            <td> {{ name }}</td>  
            <td> {{ name }}</td>    
            
            <td> {{ name  }}</td> 
            
   

                   <td> {{ name  }}</td>  
            
            <td> {{ name  }}</td>  
            <td> {{ name  }}</td> 
    

            
          
            </table>

    
      <script src="./scripts/bootstrap.min.js.download"></script>
    <script src="./scripts/docs.min.js.download"></script>
               
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script> 
 <!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.js"></script> -->

 <script src="scripts/prova2.js"></script>
      <script src="scripts/rest-services.js"></script>
    <script src="scripts/jquery.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <script src="scripts/angular.js"></script>
  <!--  <script src="scripts/emailchecker.js"></script>  --> 
    <script src="scripts/angular-bootstrap-datepicker.js" charset="utf-8"></script>
   <!-- <script src="scripts/number-directive.js"></script> -->
    <script type="application/javascript"></script>

using the controller "StaffController". But "StaffController" use some functions of another js file, a factory file, called rest-services.js:

var app = angular.module("StaffManagement");  
app.factory("restService", function($http, $window) {  
    var REST_URL = "http://localhost:8080/FoodDrinkDispener/rest/";
    var minutes = 20; // Reset when storage is more than 20 minutes
    var now = new Date().getTime();
    var setupTime = localStorage.getItem('setupTime');
    
    function _GetToken() {
        var token = localStorage.getItem("token");
        if (token !== null) 
            return JSON.parse(token);
        else
        console.log("Non c'รจ un token");
    }
    
    
    function _SetToken(CurrentToken) { //uso localStorage al posto si sessionStorage
        localStorage.setItem("token", (CurrentToken === null) ? null : JSON.stringify(CurrentToken));
    }
    
    function _deleteToken(idtoken, _success, _error) {  
       return $http({  
            method : 'DELETE',  
            url : REST_URL+'tokenstaff/'+idtoken,  
            headers : {  
                'Content-Type' : 'application/json'  
            }  
            }).then( _success, _error );  
        }
    
    function _RestSuccess(response) { //uso localStorage al posto si sessionStorage
        console.log("success"+response.status);
    }
    
    function _RestError(response) { //uso localStorage al posto si sessionStorage
        console.log("error"+response.status);
        if (response.status==404)
            $window.location.href="error404.html";
        else if(response.status==500)
            $window.location.href="error500.html";
            
    }
    
    function _DeleteByidLogin(loginform, _logsuccess, _logerror){
        return $http({  
                        method : 'GET',  
                        url : REST_URL+'stafflogin/'+loginform.email
                    }).then(function successCallback(response) {
                        _deleteToken(response.data, _logsuccess, _logerror);
                    }, function errorCallback(response) {  
                        console.log("ERRORE");
                        console.log(response.statusText);  
                    }); 
        }
    
    function _timerTokenControl(currentToken, _error){
        if(now-setupTime > minutes*60*1000) {
                if(currentToken!=null){
                    _deleteToken(currentToken.idtokenStaff, _error);
                }
                localStorage.clear();
                $window.location.href="login.html#/sessionExpired";
            }
    }
    


    
    return {
        login: function(loginform, _logsuccess, _logerror){
        _DeleteByidLogin(loginform, _logsuccess, _logerror);
            return $http({  
                method : 'POST',  
                url : REST_URL+'tokenstaff',
                data : angular.toJson(loginform), 
                }).then(function successCallback(response) {  
                    if (typeof response.data === 'object'){
                        var CurrentToken = response.data;
                        _SetToken(CurrentToken);
                        localStorage.setItem('setupTime', now)
                        
                        _logsuccess(response)
                        console.log("login andato a buon fine");
                        $window.location.href="fixed_admin.html";
                        return response.status;
                     }
                    else {
                        _SetToken(null);
                        _logerror(response);
                    }
                },function (response) {
                    _SetToken(null);
                    _logerror(response);
                }
                );
        },
        
        
        
             
        insertstaff: function(stafform, _giveLast, _error){
            var currentToken = _GetToken();

          /*  if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenStaff,
                };
            }*/
                
            _timerTokenControl(currentToken, _error);
            
            if (setupTime == null) {
                console.log("token scaduto");
                $window.location.href="login.html";
            }
            

            if (currentToken !== null) {
                return $http({  
                    method : 'POST',  
                    url : REST_URL+'staff',  
                    data : angular.toJson(stafform),  
                    headers : {  
                      token: currentToken.tokenStaff,
                        'Content-Type' : 'application/json'  
                    }  
                }).then( _giveLast, _error );
            }  else {
                    $window.location.href="login.html";
                    console.log("NON SEI LOGGATO!!!");
            }
        } ,
        
        
        /*
        insertstaff: function(stafform, _giveLast, _error){
            return $http({  
                method : 'POST',  
                url : REST_URL+'staff',  
                data : angular.toJson(stafform),  
                headers : {  
                            'Content-Type' : 'application/json'  
                }  
            }).then( _giveLast, _error );
            } ,
        */
        insertstafflogin: function(staffloginform, _giveLast, _error){
            var currentToken = _GetToken();

         /*   if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenStaff,
                };
            }*/
                
            _timerTokenControl(currentToken, _error);
            
            if (setupTime == null) {
                console.log("token scaduto");
                $window.location.href="login.html";
            }
            

            if (currentToken !== null) {
                return $http({  
                    method : 'POST',  
                    url : REST_URL+'stafflogin',  
                    data : angular.toJson(staffloginform),  
                    headers : {  
                        token: currentToken.tokenStaff,
                        'Content-Type' : 'application/json'  
                    }  
                }).then( _giveLast, _error ); //se errore allora DELETE staff, altrimenti sta stessa stafflogin
            }  else {
                    $window.location.href="login.html";
                    console.log("NON SEI LOGGATO!!!");
            }
            } ,
        
       
        
        allstaffworking: function(_getstaff, _error){
            var currentToken = _GetToken();

            if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenStaff,
                };
            }
                
            _timerTokenControl(currentToken, _error);
            
            if (setupTime == null) {
                console.log("token scaduto");
                $window.location.href="login.html";
            }
            

            if (currentToken !== null) {
            $http({  
                        method : 'GET',  
                        headers: Headers,
                        url : REST_URL+'staff/working'
                    }).then(function successCallback(response) {  
                        _getstaff(response)
                    }, function errorCallback(response) {  
                        console.log(response.statusText);  
                    });  
               }  else {
                    $window.location.href="login.html";
                    console.log("NON SEI LOGGATO!!!");
            }
        },
        
        laststaff: function(_postStaffLogin, _error){
            var currentToken = _GetToken();

            if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenStaff,
                };
            }
                
            _timerTokenControl(currentToken, _error);
            
            if (setupTime == null) {
                console.log("token scaduto");
                $window.location.href="login.html";
            }
            

            if (currentToken !== null) {
                return  $http({  
                    method : 'GET',
                    headers: Headers,
                    url : REST_URL+'staff/getlast'  
                                }).then(function successCallback(response) {
                                _postStaffLogin(response)
                                console.log(response);
                                return response.status; 
                                 //    console.log($scope.staffLast.idstaff);
                                 //   _postStaffLogin();
                            }, function errorCallback(response) {  
                                console.log(response.statusText);  
                            }); 
                }  else {
                    $window.location.href="login.html";
                    console.log("NON SEI LOGGATO!!!");
            }
        
    },
        
        deletestaff: function(stafform, _success, _error){
             var currentToken = _GetToken();

            if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenStaff,
                };
            }
                
            _timerTokenControl(currentToken, _error);
            
            if (setupTime == null) {
                console.log("token scaduto");
                $window.location.href="login.html";
            }
            

            if (currentToken !== null) {
                return $http({  
                    method : 'PUT',  
                    url : REST_URL+'staff',
                    data : angular.toJson(stafform),  
                    headers : {  
                        token: currentToken.tokenStaff,
                        'Content-Type' : 'application/json'  
                    }
                    }).then( _success, _error ); 
            }  else {
                    $window.location.href="login.html";
                    console.log("NON SEI LOGGATO!!!");
            }

            }
        
    }
    
    
});

The problem is this "restService" factory! It causes me this error:

angular.js:12520 Error: [$injector:unpr] Unknown provider: restServiceProvider <- restService <- StaffController
http://errors.angularjs.org/1.4.8/$injector/unpr?p0=restServiceProvider%20%3C-%20restService%20%3C-%20StaffController
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:68:12
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:4334:19
    at Object.getService [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:4482:39)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:4339:45
    at getService (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:4482:39)
    at invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:4514:13)
    at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:4531:27)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:9197:28
    at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js:7:268)
    at invokeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js:8841:9) <div ng-view="" class="ng-scope">

Error message

In fact, if I remove "restService" dependency and all the functions of rest-services.js from main-admin.js, it works..but I need to use some functions of restService factory from rest-services.js. How I can do?

3

There are 3 answers

0
Giacomo Brunetta On BEST ANSWER

Solved import this script in in fixed_admin.html:

<script src="scripts/rest-services.js"></script>

0
dimson d On

try not to use var app = angular.module("StaffManagement") just angular.module("StaffManagement").factory("restService", .....

you are redefining var app

0
Ram_T On
var app = angular.module("StaffManagement");

this means the app called StaffManagement is already created somewhere and you are just accessing it. But, actually you want to create this. For that, you need to be used as below.

var app = angular.module("StaffManagement", []);  

Try to include files in this order(first to last)

jquery, angular, your js files