Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS:设置变量并在$http服务外部访问它?_Angularjs - Fatal编程技术网

AngularJS:设置变量并在$http服务外部访问它?

AngularJS:设置变量并在$http服务外部访问它?,angularjs,Angularjs,我的服务有问题: app.service('admin', function($http, $scope){ // Tried $scope but no dice... var self = this; self.admin = false; $http.get("api/login.php").success(function(reply){ if(reply.realname !=null){ self.admin =

我的服务有问题:

app.service('admin', function($http, $scope){ // Tried $scope but no dice...
    var self = this; self.admin = false;
    $http.get("api/login.php").success(function(reply){
            if(reply.realname !=null){
                self.admin = true;
            } else{ self.admin = false }
    });
    alert(self.admin); // this is just for debugging purposes. I know I havent got my service setup properly yet, I want to get it working properly first.

});
我想设置我的服务$http.get,以根据请求将self.admin设置为值

另一方面: 这个请求检查你是否是一个管理员,这就是为什么我能负担得起做reply.realname=null,因为它只查找管理员用户,如果不是管理员,则不返回任何内容。

当runTarm收购时,$http返回承诺。我利用了这一点:

app.service('admin', function($http){
    self.adminOrNot = function(){
        var defer = $q.defer();
        var promise = $http.get("api/user.php");
        return promise;
    }
});
app.controller("mainController", function($scope, admin){
    var scope = $scope;
    admin.adminOrNot().then(function(data){
        if(data.data.error != null){
            scope.adminStatus = false;
        } else if(data.data.steamid != null){
            scope.adminStatus = true;
        }
    });
});
很好用!仔细想想,我可能应该把逻辑放在管理服务中。。。不管怎样,它是有效的

然后,我要做的就是在HTML中检索它:

<input type="image" src="media/admin.png" ng-hide="adminStatus">

我不确定这是否是做事情的最佳方式,但…

您可以使用它。您只需等待请求完成,直接从$http返回承诺时不需要$q。你正在用你不使用的延迟做出新的承诺。