2013-06-29 131 views
0

Angular JS新手:我得到了gapi is not defined,因爲在加載API之前調用了sydney.userAuthed。但我不明白爲什麼在創建控制器時調用方法sydney.auth。頁面加載時出現錯誤,沒有用戶交互。AngularJS控制器init

calling auth api.js:22 
ReferenceError: gapi is not defined 
    at Object.sydney.userAuthed (http://localhost:8888/js/api.js:36:8) 
    at Object.sydney.auth (http://localhost:8888/js/api.js:23:30) 
    at new LoginController (http://localhost:8888/js/controllers.js:8:24) 
    at invoke (http://localhost:8888/lib/angular/angular.js:2902:28) 
    at Object.instantiate (http://localhost:8888/lib/angular/angular.js:2914:23) 
    at http://localhost:8888/lib/angular/angular.js:4805:24 
    at updateView (http://localhost:8888/lib/angular/angular-ui-router.js:931:30) 
    at <error: illegal access> 
    at Object.Scope.$broadcast (http://localhost:8888/lib/angular/angular.js:8307:28) 
    at $state.transition.resolved.then.$state.transition (http://localhost:8888/lib/angular/angular-ui-router.js:747:20) angular.js:5754 
OAuth2 API loaded api.js:13 

ui-router限定的state爲:

function LoginController($scope, $state) { 
    $scope.auth = sydney.auth($state); 
} 

sydney.auth方法用於使用Google APIs Client Library for JavaScript認證用戶:

myapp.config(function($stateProvider, $routeProvider) { 

    $stateProvider.state('signin', { 
     url : "/", // root route 
     views : { 
      "signinView" : { 
       templateUrl : 'partials/signin.html', 
       controller: 'LoginController' 
      } 
     }, 
    }) 

作爲控制器被定義。

var sydney = sydney || {}; 

sydney.auth = function($state) { 
    console.log("calling auth"); 
    sydney.signin(false, sydney.userAuthed($state)); 
} 

sydney.signin = function(mode, callback) { 
     gapi.auth.authorize({client_id: sydney.CLIENT_ID, 
     scope: sydney.SCOPES, immediate: mode, 
     response_type: 'token id_token'}, 
     callback); 
     console.log("signin called"); 
} 

sydney.userAuthed = function($state) { 
     var request = 
      gapi.client.oauth2.userinfo.get().execute(function(resp) { 
     if (!resp.code) { 
      var token = gapi.auth.getToken(); 
      token.access_token = token.id_token; 
      gapi.auth.setToken(token); 
      // User is signed in, call my Endpoint 
      gapi.client.realestate.owner.create().execute(function(resp) { 
       alert("Signed In"); 
       $state.transitionTo("signedin"); 
      }); 
     } 
     }); 
    } 

編輯

正確的答案是定義$scope.auth作爲一個函數:

function LoginController($scope, $state) { 
    $scope.auth = function() { 
     sydney.auth($state); 
    } 
} 
+0

你有一個這樣的運動員嗎?您可以嘗試將gapi添加到函數變量,如此函數($ state,gapi) – pasine

回答

1

好像你正在試圖做的就是從你的範圍sydney.auth功能是什麼。如果是這樣,你應該改變你的LoginController到:

function LoginController($scope, $state) { 
    $scope.auth = sydney.auth; 
} 

你的代碼所做的就是調用sydney.auth功能和設置$scope.auth其返回值,這不是我想你打算。

+0

接受的答案是因爲它幫助我找到正確的解決方案。用正確的答案編輯問題。 – Sydney