【发布时间】:2017-04-24 21:13:21
【问题描述】:
我正在尝试将网络应用程序中的 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。如果我注释掉对谷歌登录的调用并从控制器调用googlelogin,则在页面加载后它工作得非常好。我不明白的是我收到了日志消息,所以似乎服务已加载并且运行了一些东西,但不是所有的东西。
【问题讨论】:
标签: javascript angularjs angular-services google-authentication