2015-12-14 487 views
2

我的角度服务存在问题。角度服务返回undefined

我的服务具有下面的代码:

app.service("Utilidades", ['$http', '$window', function ($http, $window) { 
return { 
    Get: function (urlAbsoluta, parametros, callback) { 
     var Utilidades = this; 

     $http 
      .get(app.UrlBase + urlAbsoluta, parametros) 
      .then(function (data) { 
       var Datos = angular.fromJson(data); 

       Utilidades.GuardarToken(Datos.Token); 

       callback(Datos); 
      }); 
    }, 


    ObtenerMenu: function() { 
     var Utilidades = this; 

     Utilidades.Get("Administracion/Api/Usuarios/Menu", {}, function (Datos) { 
      Datos = angular.fromJson(Datos.data); 

      if (Datos.Error == "") { 
       return Datos.Resultado; 
      } else { 
       return ""; 
      } 
     }); 
    } 
} 
}]); 

然后,在我的控制器我有下面的代码:

app.controller('LoginCtrl', ['$scope', '$http', '$location', 'Utilidades', 
function Iniciador($scope, $http, $location, Utilidades) { 
     var Li = this; 

     Li.Usuario = ""; 
     Li.Contrasena = ""; 
     Li.Error = ""; 
     Li.MenuItems = []; 

     Li.Menu = function() { 
      Li. MenuItems = Utilidades.ObtenerMenu(); 
     } 
    }] 
); 

当我运行此,Li.MenuItems具有未定义值,我不不知道为什么。

+0

你错过了','后您的服务的'回报{ ...' – Aaron

+0

发生这种情况是因为您正在做的“返回”是针对“函数(Datos){” 不适用于“ObtenerMenu:function(){”。 您在Get函数中回调了这个已知问题。我不能建议任何解决方案,我不知道一个,接受syncronic ajax这是不可接受的。 – Amit

+1

是因为李后的空间。 “Li。MenuItems = Utilidades.ObtenerMenu();” –

回答

5

return语句是一个函数里面方法ObtenerMenu所以ObtenerMenu方法实际上并没有返回任何东西。您需要提供一种方法来访问结果值:

服务

app.service("Utilidades", ['$http', '$window', function ($http, $window) { 
    return { 
     Get: function (urlAbsoluta, parametros) { 
      var Utilidades = this; 

      // v------------ return statement here 
      return $http 
       .get(app.UrlBase + urlAbsoluta, parametros) 
       .then(function (data) { 
        var Datos = angular.fromJson(data); 

        Utilidades.GuardarToken(Datos.Token); 

        // v------------ return statement here 
        return Datos; 
       }); 
     }, 


     ObtenerMenu: function() { 
      var Utilidades = this; 

      // v------------ return statement here 
      return Utilidades.Get("Administracion/Api/Usuarios/Menu", {}) 
       .then(function (Datos) { 
        if (Datos.Error == "") { 
         return Datos.Resultado; 
        } else { 
         return ""; 
        } 
       }); 
     } 
    }; 
}]); 

在控制器

Li.Menu = function() { 
    Utilidades.ObtenerMenu() 
     .then(function (resultado) { 
      Li. MenuItems = resultado; 
     }); 
} 
0

这是因为ObtenerMenu函数是异步函数。该功能最初没有(那么未定义),后来返回任何东西,一段时间后,当Ajax请求完成后,该功能已经完成了它的执行堆栈