在Angular后服务函数调用中分配$ scope变量

时间:2016-08-13 08:57:24

标签: angularjs-scope angular-services

我尝试在特定函数调用结束后为$ scope变量赋值。但由于JS引擎异步处理请求,因此在函数调用结束之前分配变量。我该如何解决这个问题。下面是我在fblogin函数调用后尝试分配$ scope变量isAuth,msg,profpic等的代码片段。

//controller
ub.controller('mainController',['$scope','$log','$http','fbauthFact','$location','$anchorScroll','$routeParams',function($scope,$log,$http,fbauthFact,$location,$anchorScroll,$routeParams){

    $scope.profpic="";
    $scope.msg={};


    $scope.fblogin= function(){
        $scope.fblogincb(function callback(){
            $scope.isAuth = fbauthFact.isAuth;
            $scope.msg= fbauthFact.msg;
            $scope.profpic=fbauthFact.profpic;
            $scope.accesstoken=fbauthFact.accesstoken;
            $log.log("$scope.msg: "+$scope.msg);
            $log.log("$scope.isAuth:"+$scope.isAuth);
        });

    };

    $scope.fblogincb=function(callback){
        fbauthFact.fblogin();  
        callback();
    };    
}]);

//service

    ub.service('fbauthFact',["$http","$log","$rootScope",function($http,$log,$rootScope){

        this.isAuth=false;
        this.profpic=""
        this.fbresponse={};
        this.msg="";
        var self=this;
        self.testAPI =function() {
            FB.api('/me',{fields: 'first_name,last_name,gender,email,picture'}, function(response) {

                this.fbresponse = response;
                this.profpic = response.picture.data.url;
                this.isAuth=true;
                this.accesstoken = FB.getAuthResponse().accessToken;

                document.getElementById('status').innerHTML =
                'Thanks for logging in, ' + response.first_name + '!';
                document.getElementById('profpic').innerHTML =
                "<img src='" + response.picture.data.url + "'>";


                $http({
                method:"GET",
                url: "http://localhost:3000/api/creaprof",
                params: response
                }).then(function successCallback(srresponse){
                        this.msg=srresponse.data;    
                        $log.log("http get request success: "+this.msg);
                        },
                        function errorCallback(srresponse){
                            $log.log("http get request failure"+srresponse.data);
                        });

                $rootScope.$apply();

            });//FB.api call back function


        };//testAPI

        this.fblogin =function(){
            FB.login(function(response){

                if (response.status === 'connected') {
                  // Logged into your app and Facebook.
                  self.testAPI();
                } else if (response.status === 'not_authorized') {
                  // The person is logged into Facebook, but not your app.
                  document.getElementById('status').innerHTML = 'Please log ' +
                    'into this app.';
                } else {
                  // The person is not logged into Facebook, so we're not sure if
                  // they are logged into this app or not.
                  document.getElementById('status').innerHTML = 'Please log ' +
                    'into Facebook.';
                }       
            });       
        };//fblogin


    }]);

2 个答案:

答案 0 :(得分:0)

在您的服务中,更改下面的fblogin方法,以便它返回一个承诺。

this.fblogin =function(){
        FB.login(function(response){
            var deferred = $q.defer();
            if (response.status === 'connected') {
              // Logged into your app and Facebook.
              deferred.resolve('connected');
              self.testAPI();
            } else if (response.status === 'not_authorized') {
              // The person is logged into Facebook, but not your app.
              deferred.reject('not_authorized');
              document.getElementById('status').innerHTML = 'Please log ' +
                'into this app.';
            } else {
              // The person is not logged into Facebook, so we're not sure if
              // they are logged into this app or not.
              deferred.reject('not_logged_in');
              document.getElementById('status').innerHTML = 'Please log ' +
                'into Facebook.';
            }   
            return deferred.promise;    
        });       
    };//fblogin

然后在你的控制器中称之为

$scope.fblogin=function(){
    fbauthFact.fblogin().then(function(response){
        //assign your variables if login is successfull
    },function(response){
        // do smt if not_authorized or not_logged_in
    }) 
};   

答案 1 :(得分:0)

谢谢@Salih。你的回答帮助我使用$ q服务并承诺解决我的问题。但我不得不在不同的地方使用它。这是我的工作代码。

//controller

ub.controller('mainController',['$scope','$log','$http','fbauthFact','$location','$anchorScroll','$routeParams',function($scope,$log,$http,fbauthFact,$location,$anchorScroll,$routeParams){

    $scope.profpic="";
    $scope.msg={};
    $scope.isAuth = false;



    $scope.fblogin= function(){
        fbauthFact.fblogin().then(
                function(response){
                $scope.isAuth = fbauthFact.isAuth;
                $scope.msg= fbauthFact.msg;
                $scope.profpic=fbauthFact.profpic;
                $scope.accesstoken=fbauthFact.accesstoken;
                //$scope.$apply();
                $log.log("fblogin() - success :"+response);
                $log.log("$scope.msg: "+$scope.msg);
                $log.log("$scope.isAuth:"+$scope.isAuth);
                $log.log("$scope.profpic:"+$scope.profpic);

            },function(reason){
                 $log.log("fblogin() - failure :Need to login to the application :"+reason);
            })

        };

}]);

//factory
ub.service('fbauthFact',["$http","$log","$rootScope","$q",function($http,$log,$rootScope,$q){

    this.isAuth=false;
    this.profpic=""
    this.fbresponse={};
    this.msg="";
    var self=this;

    self.testAPI =function() {
        var tAdef = $q.defer();
        FB.api('/me',{fields: 'first_name,last_name,gender,email,picture'}, function(response) {
            self.fbresponse = response;
            self.profpic = response.picture.data.url;
            self.isAuth=true;
            self.accesstoken = FB.getAuthResponse().accessToken;
            // console.log('Successful login for: ' + response.first_name);
            //console.log('email:' + (response.email));
            document.getElementById('status').innerHTML =
            'Thanks for logging in, ' + response.first_name + '!';
            document.getElementById('profpic').innerHTML =
            "<img src='" + response.picture.data.url + "'>";


            //$scope.profpic = authFact.profpic;

            //$log.log('profpic:'+$scope.profpic);
            //$log.log('isAuth:'+$scope.isAuth);
            //$log.log('$scope.fbresponse :'+$scope.fbresponse );

            $http({
            method:"GET",
            url: "http://localhost:3000/api/creaprof",
            params: response
            }).then(function successCallback(srresponse){
                    self.msg=srresponse.data;    
                    $log.log("http get request success: "+self.msg);
                    tAdef.resolve('http get request success');
                    },
                    function errorCallback(srresponse){
                        $log.log("http get request failure:"+srresponse.data);
                        tAdef.reject('http get request failure');
                    });

            $rootScope.$apply();

        });//FB.api call back function

        return tAdef.promise;

    };//testAPI

    this.fblogin =function(){
        var deferred = $q.defer();
        FB.login(function(response){

            if (response.status === 'connected') {
              // Logged into your app and Facebook.
                 self.testAPI().then(
                 function(resolved){
                     $log.log('testAPI() - success');
                    deferred.resolve('connected');    
                 },
                function(rejected){
                    $log.log('testAPI() - failure');
                    deferred.reject('error connecting');
                });

            } else if (response.status === 'not_authorized') {
              // The person is logged into Facebook, but not your app.
                deferred.reject('not_authorized');
                document.getElementById('status').innerHTML = 'Please log ' +
                'into this app.';
            } else {
              // The person is not logged into Facebook, so we're not sure if
              // they are logged into this app or not.
                 deferred.reject('not logged in');
                document.getElementById('status').innerHTML = 'Please log ' +
                'into Facebook.';
            } 

        }); 
        return deferred.promise;
    };//fblogin

}]);