0

각도 서비스로 웹 앱에 Google 로그인을 넣으려고합니다. 그러나 내가 잘못하고있는 것을 파악할 수 없습니다. 내가 페이지, 콘솔 로그 예상대로 service started를로드,하지만 내가 오류 TypeError: Cannot read property 'getAuthInstance' of undefined을 얻을 때각도 서비스가 특급으로 작동하지 않습니다

여기 내 서비스

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


}); 

입니다. Google 로그인 호출에 댓글을 쓰고 컨트롤러에서 googlelogin으로 전화를 걸면 페이지가로드 된 후 정상적으로 올바르게 작동합니다. 내가 이해할 수없는 것은 로그 메시지를 받는다는 것입니다. 따라서 서비스가로드되고 실행되는 것으로 보이지만 모든 것이 아닌 것으로 보입니다.

답변

1

gapi.load('auth2', ...) 콜백 내에 this.googlelogin(); 호출을 배치해야합니다. 초기화되기 전에 호출하고 있습니다.

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의 예제와 매우 유사합니다.

+0

그것은 "마법처럼"작동하지만, 이것은 내가 잘 이해하지 못하는 비동기적인 신비의 일부라고 생각합니다. (나는 아직 희망합니다 ...). 여기서 일어나는 일은 하나씩 차례대로 실행된다는 것입니다. 그러나 콜백이 있기 때문에'gapi.load'를 기다리지 않습니다. 그래서 우리는 그것을 넘겨주고 그것에 의존하는 모든 것은 콜백이되어야합니다. 권리? – fbence

+1

'gapi.load (...) '를 호출하면 원하는 API를 호출하지만 응답을 기다리지 않습니다 (비동기식이므로 비 블로킹). 응답은 다른 이벤트 루프에서 트리거되는 콜백 함수에서 사용할 수 있습니다. https://developer.mozilla.org/cs/docs/Web/JavaScript/EventLoop에서 이것에 대해 몇 가지 기본 정보를 제공해야합니다. 'gapi.load'를 호출하는 것은'setTimeout'을 사용한 예제와 매우 비슷합니다. –

관련 문제