简体   繁体   中英

AngularJS pass service variable to controller

I built a simple app with user authentication base on this: link

Basically, I have a userAccountService, responsible for communicating with server and login controller handling the login process.

From other controller I want to check if user is already logged in (to hide LogIn button, and show user profile instead).

So I have a navController

function navCtrl ($scope, $modal, userAccountService) {

    $scope.IsUserLoggedIn = function () {
        return userAccountService.isUserLoggedIn;
    } 

}

So in HTML I use this ng-hide="isUserLoggedIn()

my userAccountService:

app.factory('userAccountService', ['$http', '$q', userAccountService]);

function userAccountService($http, $q) {

    var service = {
        registerUser: registerUser,
        loginUser: loginUser,
        logOut: logOut,
        getValues: getValues,
        isUserLoggedIn: false,
        accessToken: ""
    };

    // code ommited
    function loginUser(userData) {
        var tokenUrl = serverBaseUrl + "/Token";
        if (!userData.grant_type) {
           userData.grant_type = "password";
        }

        var deferred = $q.defer();

        $http({
            method: 'POST',
            url: tokenUrl,
            data: userData,
        })
            .success(function (data,status,headers,cfg) {
                // save the access_token as this is required for each API call. 
                accessToken = data.access_token;
                isUserLoggedIn = true;
                // check the log screen to know currently back from the server when a user log in successfully.
                console.log(data);
                deferred.resolve(data);
            })

            .error(function (err, status) {
                console.log(err);
                deferred.reject(status);
            });

        return deferred.promise;
    }
}

What am I doing wrong? Here's another interesting read I took inspiration from: link

You can't return a variable, but you can return a function, so create a function that returns that variable.

Try something like this, it returns your service object (you might want to put a $watch on it):

Service

function userAccountService($http, $q) {

  function getData() {
      return service;
  }
  ...
}

Controller

$scope.IsUserLoggedIn = userAccountService.getData().isUserLoggedIn;

Also, you're not correctly updating the state variable from your success callback - you're creating global variables instead of using the service object properties. So, for example:

isUserLoggedIn = true;

should be:

service.isUserLoggedIn = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM