0

我想將谷歌登錄在一個Web應用程序到一個角度的服務,但我無法弄清楚我做錯了什麼。角度服務不工作作爲exp

這裏是我的服務

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,則在頁面加載完成後,它的工作情況絕對沒問題。我不明白的是我得到了日誌消息,所以看起來服務已經加載並且運行了一些東西,但並不是所有的東西。

回答

1

您應該將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.loadsetTimeout的示例非常相似。

+0

它「神奇」的作品,但在我看來,這是一些異常的神祕,我不明白很好(我希望...)。所以這裏發生的事情是一個接一個地執行,但是我們不會等待'gapi.load',因爲它有一個回調函數,所以我們把它傳遞過來,依賴它的所有東西都應該進入它的回調函數,對? – fbence

+1

當你調用'gapi.load(...)'時,它會調用所需的API,但不會等待響應(所以它是異步的,非阻塞的)。該回應將在回調函數中可用,該回調函數將在另一個事件循環中觸發。看看這個:https://developer.mozilla.org/cs/docs/Web/JavaScript/EventLoop,它應該爲你提供一些關於這方面的基礎知識。調用'gapi.load'與'setTimeout'的例子非常相似。 –