在模块中做出承诺

时间:2015-08-30 16:57:18

标签: angularjs cordova angularjs-factory angularjs-module angularjs-injector

我尝试在我的应用中制作Facebook注册模块。 Facebook API比我的Angular控制器更快,所以应该在这里使用promise。问题是$ q似乎是一个空对象,延迟函数是未定义的。

模块:

var module = angular.module('app.facebook',[]);     module.constant(“fbAppId”,'herecomesmycode');

module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$q', '$ionicPlatform', '$state', 'authService', 'datacontext', '$location'];

function FacebookAPI(UserService, $q, $ionicLoading, fbAppId, $state, authService, datacontext, $location) {
    return {
        fbLoginSuccess: fbLoginSuccess,
        fbLoginError: fbLoginError,
        getFacebookProfileInfo: getFacebookProfileInfo,
        fbLogin: fbLogin,
        fbRegister: fbRegister

    };

这里$ q.defer未定义:

    function fbRegister() {

        console.log($q.defer);
        if (!cordova) {
            facebookConnectPlugin.browserInit(fbAppId);
        }
        var data;
        facebookConnectPlugin.getLoginStatus(function (response) {
            if (response.status !== 'connected') {
                facebookConnectPlugin.login(["email"],
                    function(response) {
                        data = getApiData();
                    },
                    function(response) {
                    });
            } else {
                data = getApiData();
            }
        });
    }

不使用promise,它可以从API中获得快速,但是我希望用API填充值的所有变量都是在API完成之前启动的,并且是未定义的。

1 个答案:

答案 0 :(得分:0)

整个模块:

(function() {
'use strict';

var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'myappkey');

module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$ionicPlatform', '$state', 'authService', '$q'];

function FacebookAPI(UserService, $ionicLoading, fbAppId, $state, authService, $q) {
    return {
        fbLoginSuccess: fbLoginSuccess,
        fbLoginError: fbLoginError,
        getFacebookProfileInfo: getFacebookProfileInfo,
        fbLogin: fbLogin,
        fbRegister: fbRegister
    }

    function fbRegister() {

        console.log($q);
        if (!cordova) {
            facebookConnectPlugin.browserInit(fbAppId);
        }
        var data;
        facebookConnectPlugin.getLoginStatus(function (response) {
            if (response.status !== 'connected') {
                facebookConnectPlugin.login(["email"],
                    function(response) {
                        data = getApiData();
                    },
                    function(response) {
                    });
            } else {
                data = getApiData();
            }
        });
    }

    function getApiData() {
        var formData = {};

        facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email,birthday", ["public_profile", "email", "user_birthday"],
            function (result) {
                if (result.gender == "male") {
                    result.gender = '1';
                } else {
                    result.gender = '2';
                }
                formData = {
                    name: result.first_name + " " + result.last_name,
                    email: result.email,
                    birthday: new Date(result.birthday),
                    gender: result.gender
                }

                console.log("moduł" + formData);//here we have nice and neat data
                return formData;

            }, function(res) {

            });

    }

    };

    //This is the success callback from the login method
    function fbLoginSuccess(response) {

        var fbLogged = $q.defer();

        if (!response.authResponse) {
            fbLoginError("Cannot find the authResponse");
            return;
        }
        var expDate = new Date(
            new Date().getTime() + response.authResponse.expiresIn * 1000
        ).toISOString();


        var authData = {
            id: String(response.authResponse.userID),
            access_token: response.authResponse.accessToken,
            expiration_date: expDate
        }

        authService.facebookLogin(response.authResponse.accessToken).then(function() {
            fbLogged.resolve(authData);
        });

    };

    //This is the fail callback from the login method
    function fbLoginError(error) {

        var fbLogged = $q.defer();
        fbLogged.reject(error);
        alert(error);
        $ionicLoading.hide();
    };

    //this method is to get the user profile info from the facebook api
    function getFacebookProfileInfo() {
        var info = $q.defer();
        facebookConnectPlugin.api('/me', "",
            function(response) {
                info.resolve(response);
            },
            function(response) {
                info.reject(response);
            }
        );
        return info.promise;
    }

    //This method is executed when the user press the "Login with facebook" button
    function fbLogin() {
        if (!cordova) {
            //this is for browser only
            facebookConnectPlugin.browserInit(fbAppId);
        }

        //check if we have user's data stored
        var user = UserService.getUser();


        facebookConnectPlugin.getLoginStatus(function(success) {
            //alert(JSON.stringify(success, null, 3));
            if (success.status === 'connected') {
                // the user is logged in and has authenticated your app, and response.authResponse supplies
                // the user's ID, a valid access token, a signed request, and the time the access token
                // and signed request each expire

                facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email", ["public_profile", "email"],
                    function(result) {
                        //alert("Result: " + JSON.stringify(result));
                        //alert(result.first_name);
                    })

                var accessToken = success.authResponse.accessToken;

                authService.facebookLogin(accessToken).then(function() {
                    $state.go('app.map');
                }, function(err) { alert('auth failed: ' + JSON.stringify(err, null, 2)); });


            } else {
                //if (success.status === 'not_authorized') the user is logged in to Facebook, but has not authenticated your app
                //else The person is not logged into Facebook, so we're not sure if they are logged into this app or not.

                $ionicLoading.show({
                    template: 'Loging in...'
                });

                // permissions from facebook
                facebookConnectPlugin.login([
                    'email',
                    'public_profile',
                    'user_about_me',
                    'user_likes',
                    'user_location',
                    'read_stream',
                    'user_photos'
                ], fbLoginSuccess, fbLoginError);

                fbLogged.promise.then(function(authData) {

                    var fb_uid = authData.id,
                        fb_access_token = authData.access_token;

                    //get user info from FB
                    getFacebookProfileInfo().then(function(data) {

                        var user = data;
                        user.picture = "http://graph.facebook.com/" + fb_uid + "/picture?type=large";
                        user.access_token = fb_access_token;
                        //save the user data
                        //store it on  local storage but it should be save it on a database
                        UserService.setUser(user);

                        $ionicLoading.hide();
                        $state.go('app.map');
                    });
                });
            }
        });
    }

})();