【问题标题】:Making promises in modules在模块中做出承诺
【发布时间】:2015-11-24 18:22:44
【问题描述】:

我尝试在我的应用中制作 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();
            }
        });
    }

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

【问题讨论】:

  • 那么console.log($q)给了什么?
  • 它返回“未定义”。错误消息是“无法获得未定义的属性延迟”
  • 帮助我们更好地连接点。现在,您展示了您的 FacebookAPI 工厂返回了一个对象,该对象附加了一堆函数。这些函数是在工厂内部声明的吗? (例如:粘贴您的整个工厂,然后删除不相关的功能)。现在,您可以说 $q 未定义 b/c 该函数未在工厂内声明。另外,不相关(但会成为问题),请确保Facebook.$inject 中的项目在工厂函数中以相同的顺序列出。
  • 不确定这是否只是因为您的问题的布局,而是 fbRegister 放置在 FacebookAPI 函数内?
  • 嗯,在我发布之后,我发现他们在外面。我把相关的功能放进去(我现在不需要其余的,我只是当时准备,希望它们能工作)仍然没有

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


【解决方案1】:

整个模块:

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

})();

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2016-12-02
    • 1970-01-01
    相关资源
    最近更新 更多