How do I write a service that return true/false in AngularJS?

I had been reading up on AngularJS Factory and Services and came across a lot of examples. But I'm not understanding the logic behind them and can't get them to work either.

myApp.service('loginCheck', function(Facebook) {
this.loggedIn = false;
Facebook.login(function(response) {
    if (response.status == 'connected') {
        this.loggedIn = true;
    }
});
});

I need to get this service to return the loggedIn variable, if my idea of the concept is right. Should I use a factory instead? I need to store this variable all along, without making the call again every once I need it. How can I do it. I couldn't really understand the difference between factory and service. I'm a beginner here.

if(loginCheck.loggedIn){
    console.log("logged in!");
}
else{
    console.log("not logged in :/")
}

Thank you.


You can do this,

app.service('MyUser', [function($scope) {
  this.loggedIn = false;
  return {
    getStatus: function() {
       //call fb api
       this.loggedIn = true;
       return this.loggedIn;
    }
  }
}]);

DEMO

var app = angular.module('app', []);
app.controller('loginController',['$scope', 'MyUser',function($scope, MyUser)
{
    $scope.isloggedin = MyUser.getStatus();
    alert($scope.isloggedin);
}]);
app.service('MyUser', [function($scope) {
  this.loggedIn = false;
  return {
    getStatus: function() {
       this.loggedIn = true;
       return this.loggedIn;
    }
  }
}]);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
</head>
<body ng-app="app" ng-controller="loginController">
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>   
</body>
</html>

Define a factory and passed to your controller as dependency.

var myApp = angular.module('myApp', []);
myApp.factory('loginCheck', ["Facebook", function(Facebook) {
  var object = {
    loggedIn: false,
    loginFacebook: function() {
      // do facebook login here:
      //Facebook.login(function(response) {
      //  if (response.status == 'connected') {
          object.loggedIn = true;
      //  };
      }
    };

  object.loginFacebook();
  return object;
}]);

myApp.controller('myCtrl', ['loginCheck', '$scope', function(loginCheck, $scope) {
  $scope.loggedIn = loginCheck.loggedIn;
}]);

check this jsFiddle sample here.

I don't know about facebook authentication, but I think these links may help you : https://blog.brunoscopelliti.com/facebook-authentication-in-your-angularjs-web-app/ , https://developers.facebook.com/docs/javascript/howto/angularjs

To find different between service and factory look at this question or this link.

链接地址: http://www.djcxy.com/p/77834.html

上一篇: 在Angular指令中递归

下一篇: 我如何编写一个在AngularJS中返回true / false的服务?