0

Я пытаюсь сделать модуль регистрации facebook в своем приложении. Facebook API быстрее, чем мой угловой контроллер, поэтому обещание должно быть использовано здесь. Проблема в том, что $ q представляется пустым объектом, а функция отсрочки не определена.Выполнение обещаний в модулях

модуль:

вар модуль = 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 отделки и не определены.

+0

Так что же дает 'console.log ($ q)' give? – Bergi

+0

возвращает "undefined". Сообщение об ошибке было «не может получить отсрочку свойства undefined или так» –

+1

Помогите нам соединить точки лучше. Прямо сейчас вы показываете фабрике 'FacebookAPI', возвращающую объект, к которому прилагается множество функций. Объявлены ли эти функции внутри фабрики? (например: вставьте весь завод, затем удалите ненужные функции). Прямо сейчас вы можете сказать, что $ q не определено b/c, функция не объявлена ​​внутри фабрики. Кроме того, несвязанный (но будет проблемой), убедитесь, что элементы в 'Facebook. $ Inject' указаны в том же порядке в заводской функции. –

ответ

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

})();

Смежные вопросы