0

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

模块:

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();
            }
        });
    }

如果不使用承诺,它会从 API 快速获取,但我想用 API 中的值填充的所有变量都在 API 完成之前启动并且未定义。

4

1 回答 1

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');
                    });
                });
            }
        });
    }

})();

于 2015-08-30T18:02:31.273 回答