1

我使用的是Google Web Components的google-signin元素,但我不知道如何返回用户信息。google-signin不返回用户信息

<google-signin 
     client-id="{{my-id}}" scopes="email profile" 
     signed-in="{{signedIn}}"></google-signin> 

我试图写一些JS函数,但它没有工作。

function (signedIn) { 
     var profile = gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile(); 
     console.log('Name: ' + profile.getName()); 
     console.log('Image: ' + profile.getImageUrl()); 
    } 

对不起,如果这是愚蠢的问题,但我不擅长网络开发。 谢谢你的建议。

回答

3

从聚合物文档:

The google-signin-success event is triggered when a user successfully authenticates and google-signin-failure is triggered when this is not the case. Both events will also provide the data returned by the Google client authentication process. You can also use isAuthorized attribute to observe authentication state.

Additional events, such as google-signout-attempted and google-signed-out are triggered when the user attempts to sign-out and successfully signs out.

The google-signin-necessary event is fired when scopes requested via google-signin-aware elements require additional user permissions.

https://elements.polymer-project.org/elements/google-signin

<google-signin ... id="myLoginIn"></google-signin> 
<script> 
    var t = document.querySelector('#t'); 

    t.addEventListener('google-signin-success', function(data) { 
    ... 
    }); 
</script> 

或者你可以使用:

<google-signin client-id="{{my-id}}" scopes="email profile" signed-in="{{signedIn}}"></google-signin> 

<google-signin-aware 
     scopes="{{scope}}" 
     signed-in="{{signedIn}}" 
     is-authorized="{{isAuthorized}}" 
     need-additional-auth="{{needAdditionalAuth}}" 
     on-google-signin-aware-success="handleSignIn" 
     on-google-signin-aware-signed-out="handleSignOut"></google-signin-aware> 

然后你就可以得到用户名的名字那样:

var aware = document.querySelector('#awareness'); 
aware.handleSignIn = function(response) { 
     console.log('[Aware] Signin Response', response); 
     var userName = gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile().getName(); 
}; 

在这里您可以找到完整的演示:https://github.com/GoogleWebComponents/google-signin/blob/master/demo/index.html

+0

感谢传感器,很好的解释。当我在浏览器中运行它时,我成功地获得了google-signin-aware的工作和功能,但是当我在设备上运行它时,我在handleSignIn中获得了以下内容:“Uncaught TypeError:无法读取null属性'currentUser' 。当我通过Android Studio运行它时,或者在将我的客户端ID更改为Android之后生成签名的apk时,会发生这种情况。任何帮助表示赞赏。 –