1

我正在尝试使用Google Client API来访问一些用户数据以与 Coffeescript 进行比赛。

到目前为止,我使用以下代码成功访问了第一次登录的数据:

initSignIn= () ->
  gapi.load('client:auth2', initClient)

  # Init click function for sign in button
  $('#signin-button').on 'click', (e) ->
    gapi.auth2.getAuthInstance().signIn()
    return false
  return


initClient= () ->
  # Init the client API
  $.when(
    gapi.client.init({
      apiKey: 'AIzxxx',
      discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
      clientId: '31xxx.apps.googleusercontent.com',
      scope: 'profile https://www.googleapis.com/auth/youtube.readonly'
    })
  ).then(
    # Add listeners for sign in changes
    gapi.auth2.getAuthInstance().isSignedIn.listen( updateSigninStatus )
    updateSigninStatus( gapi.auth2.getAuthInstance().isSignedIn.get() )
  )
  return


 updateSigninStatus= (isSignedIn) ->
  # If the user is signed in then make the call for getting the user data
  if isSignedIn then makeApiCall()
  return


makeApiCall= () ->
  # Test logs
  console.log "gapi.client"
  console.log gapi.client
  console.log "gapi.client.people"
  console.log gapi.client.people

  # Getting the user data
  gapi.client.people.people.get({
    resourceName: 'people/me',
    'requestMask.includeField': 'person.names,person.email_addresses',
    requestMask: {
      includeField: 'person.names,person.email_addresses'
    }
  }).then(
    (response) ->
      apiCalled = false
      console.log(response);
      console.log('Hello, ' + response.result.names[0].givenName)

      return
    (reason) ->
      apiCalled = false
      console.log('Error: ' + reason.result.error.message)
      return
  )
  return

当我刷新浏览器时,有时我仍然会得到数据。但通常会出现无法加载“人”属性的接缝。我在控制台中打印出客户端对象,然后立即打印出 people 属性。它向我展示了包含人员对象的客户端对象,但下一行它无法再读取人员对象:

API调用的控制台日志

我在这里做错了吗?这是我第一次使用客户端 API。谢谢你的帮助!

4

0 回答 0