Вход в Google не распознает вход в функцию обратного вызова в Angular

Я создаю небольшое приложение Angular и использую Google Sign-In. Я просто использую пример кода из учебника, который дает Google.

              <span class="g-signin"
                data-scope="https://www.googleapis.com/auth/plus.login"
                data-clientid="blah"
                data-redirecturi="postmessage"
                data-accesstype="offline"
                data-cookiepolicy="single_host_origin"
                data-callback="signInCallback">
              </span>

Это элемент, который делает кнопку для входа, и я запускаю этот код, чтобы начать

(function () {
  var po = document.createElement('script');
  po.type = 'text/javascript';
  po.async = true;
  po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(po, s);
})();

, все они скопированы из Google. Затем у меня есть этот метод в моем контроллере,

.controller('splashController', ['$scope', '$window', function($scope, $window){
        $scope.googleLogin() = function(){
                $scope.googleAuthResult = $window.googleAuthResult;
                console.log($scope.googleAuthResult);
        };


        window.signInCallback = function(authResult){
                console.log("happy");
        };
}])

Но проблема в том, что после запуска скрипта google+ он ищет за пределами Angular World эту функцию signInCallback, которую я хочу сохранить в Angular, потому что я хочу отправить токен через angular, а не как jQuery. Какие-либо предложения?


person Hudson Buddy    schedule 16.12.2013    source источник
comment
Я предполагаю, что это из-за того, что вы не внедрили правильный сервис или не сообщили Angular о $window или что-то в этом роде, но я не могу понять это.   -  person Hudson Buddy    schedule 17.12.2013
comment
Можете ли вы переместить (function() в контроллер или в модуль .run()? Это может помочь.   -  person Zack Argyle    schedule 17.12.2013
comment
я попытался поместить функцию anon в модуль запуска, но это не меняет того факта, что скрипт google+ хочет видеть функцию не в Angular... хотя мне больше нравится run(), потому что он чище.   -  person Hudson Buddy    schedule 21.12.2013


Ответы (1)


Попробуйте использовать метод gapi.auth.authorize. Он вызывает ту же функциональность, что и кнопка, но явно через Javascript, а также позволяет вам передать метод обратного вызова в области вашего контроллера/сервиса/что угодно. Вот моя функция входа:

var authParams =                    // Define a params object for gapi.auth.authorize
{
    client_id       : '****-****.apps.googleusercontent.com',
    scope           : 'https://www.googleapis.com/auth/userinfo.email',
    immediate       : false,
    cookiepolicy    : 'single_host_origin'
};

/**
 * Authenticates the user and authorizes the local browser's JS GAPI Client, returns an object
 * with the GAPI Client's login token or false if it's not yet available, and the deferred 
 * object whose promise will be resolved when the JS GAPI Client authenticates.
 *
 * @param hard      If {{ hard }} is truthy, force the GAPI Client to reauthenticate the user
 *                  and reauthorize the client.  Ensures the client is logged in and the session
 *                  stays active even if it is disrupted external to the application.
 */
this.login = function(hard)
{
    // @TODO:   Consolidate into (!hard && (token || pending) if token can be guaranteed falsey
    //          while pending otherwise ret.logged is unreliable.  
    //          Where's a logical XOR when you need one?
    //////////////////////////
    // If a login is pending and we're not forcing a hard reauth, return the deferred object
    // promising the authorization response and 'logged':false
    if (pending && !hard) return { logged : false, deferred : deferred };

    // If the token is already set and we're not forcing a hard reauth, resolve the deferred
    // promise immediately and return it along with 'logged':token
    if (token && !hard)
    {
        deferred.resolve(token); // Resolve the promise immediately, no login response to wait for
        return { logged : token, deferred : deferred };
    }
    /////////////////////////

    deferred = $q.defer();  // We need to wait for gapi.auth.authorize to respond, reinit the promise
    pending = true;         // Don't restart the process on future calls if an authorization is pending
    gapi.auth.authorize(authParams,this.handleAuthResult);  // Authorize the client, then run the callback

    // Not logged in, return the deferred object
    return { logged : false, deferred : deferred};
}

Все содержится в сервисе.

person citizenslave    schedule 11.02.2014
comment
Для получения более актуальной информации вы можете перейти сюда — разработчикам. .google.com/api-client-library/javascript/start/ Справочник по API для клиентской библиотеки JS находится здесь — developers.google.com/api-client-library/javascript/reference/ - person James L.; 26.01.2017