在 View AngularJS 中使用服务

2024-04-12

我对 angularJS 服务有疑问。

我有简单的服务:

angular.module('mainApp.services', []).factory('AuthService',
function ($http) {
    //var currentUser = null;
    //var authorized = false;

    //AutoLogin for testing
    var currentUser={email: "[email protected] /cdn-cgi/l/email-protection", id: "15"};
    var authorized=true;

    // initial state says we haven't logged in or out yet...
    // this tells us we are in public browsing
    var initialState = false;

    return {
        initialState:function () {
            return initialState;
        },
        login:function (userData) {
            //Call API Login
            currentUser = userData;
            authorized = true;
            initialState = false;
        },
        logout:function () {
            currentUser = null;
            authorized = false;
        },
        isLoggedIn:function () {
            return authorized;
        },
        currentUser:function () {
            return currentUser;
        },
        authorized:function () {
            return authorized;
        }
    };
});

然后我有一个简单的控制器

.controller('NavbarTopCtrl', ['$scope','$modal','AuthService',function($scope,$modal,authService) {
    $scope.authService=authService;  //IS good practice?
    console.log($scope);
}])

我无法在 View 中使用我的服务。我做了一个简单的技巧并且效果很好。

$scope.authService=authService

但是如何在我的视图(HTML 文件)中调用没有此服务的服务?


在视图内使用服务通常是一种不好的做法。 视图应该只包含表示逻辑。 在您的示例中,您可以尝试仅传递用户对象,而不是将整个服务传递给视图。例如$scope.currentUser = authService.currentUser().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 View AngularJS 中使用服务 的相关文章

随机推荐