angular 服务不作为 exp

angular service not working as exp

我正在尝试将 Web 应用程序中的 google 登录信息放入 angular 服务中,但我不知道我做错了什么。

这是我的服务

angular.module('sensdogserver.services', [])

.service('AuthenticationService', function ($window,$http) {
    console.log("service started")

    gapi.load('auth2', function() {//load in the auth2 api's, without it gapi.auth2 will be undefined

            gapi.auth2.init(
                    {
                        client_id: 'CLIENT_ID',

                    }
            );
    });


    this.googlelogin = function(){
        var GoogleAuth  = gapi.auth2.getAuthInstance();
        GoogleAuth.signIn().then(function(googleUser){//request to sign in
        var profile = googleUser.getBasicProfile();

        username = profile.getName();
        $window.localStorage['username'] = username;
        googleUser = googleUser;
        googletoken = googleUser.getAuthResponse().id_token;
        console.log("google token: " + googletoken);
        $http.get("/api/auth/google/token",{headers:{'id_token':googletoken}}).success(function(data){console.log(data)}).error(function(data){console.log(data)});
        }

        )};


    this.googlesignout =function() {
        var auth2 = gapi.auth2.getAuthInstance();
        console.log("signing out: ", username);
        auth2.signOut().then(function () {
        googleUser = null;
        googletoken = null;
        username = null;
          console.log('User signed out.');
        });
    }

    var googleUser = null;
    var googletoken = null;
    var username = null;

    this.googlelogin();


});

当我加载页面时,控制台按预期记录 service started,但随后出现错误 TypeError: Cannot read property 'getAuthInstance' of undefined。如果我注释掉对 google 登录的调用并从控制器调用 googlelogin ,则在页面加载后它工作得很好。我不明白的是我收到了日志消息,所以似乎服务已加载并且某些东西正在运行,但不是所有东西。

您应该将 this.googlelogin(); 调用放在 gapi.load('auth2', ...) 回调中。您在初始化之前调用它。

angular
  .module('sensdogserver.services', [])
  .service('AuthenticationService', function ($window,$http) {
    console.log("service started")

    gapi.load('auth2', function() {
      gapi.auth2.init({
        client_id: 'CLIENT_ID',
      });
      console.log('gapi.load callback triggered');
      this.googlelogin(); // call it here in the load callback
    }.bind(this));

    this.googlelogin = function(){
      // ...
    };

    this.googlesignout = function() {
      // ...
    }

    // ...
    console.log('this will be printed before the gapi.load callback');
  });

我在加载回调和您用来调用 googlelogin 函数以突出显示问题的地方添加了日志记录。

gapi.load() 调用是异步的(非阻塞)- 当您调用它时,它会调用所需的 API,但不会等待响应。响应将在回调函数中可用,回调函数将在另一个事件循环中触发(在主程序块之后,调用 gapi.load() 函数的地方)。

看看这个:https://developer.mozilla.org/cs/docs/Web/JavaScript/EventLoop,它应该为您提供一些关于此的基础知识。调用 gapi.load 与调用 setTimeout 的示例非常相似。