"未捕获的TypeError:无法读取属性' people'未定义"

时间:2014-05-25 23:03:09

标签: javascript google-plus

我正在尝试使用Plus API对用户进行签名。我在控制台中收到以下错误:

Uncaught TypeError: Cannot read property 'people' of undefined

这是我加载和获取个人资料信息的逻辑:

var firstName;
$(document).ready(function () {
  function loadGApi() {
    gapi.client.load('plus', 'v1');
  }
  $('#loaderror').hide();
});

function signInCallback(authResult) {
  if (authResult['status']['signed_in']) {
    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    $('#gConnect').hide();
    $('#authOps').show('slow');
    $('#profile').append(
      $('<p>Hello ' + getProfile(firstName) + '</p>'));
    console.log(authResult);

  } else {
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}

function getProfile(profile) {
  var request = gapi.client.plus.people.get({
    'userId': 'me'
  });
  if (profile == firstName) {
    request.execute(function (gprofile) {
      return gprofile.displayName;
    });
  }
}

这就是我加载脚本的方式:

(function() {
  var po = document.createElement('script');
  po.type = 'text/javascript'; po.async = true;
  po.src = 'https://plus.google.com/js/client:plusone.js?onload=loadGApi';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(po, s);
})();

如果这是一个菜鸟问题我很抱歉,但我希望了解有关Javascript和使用G + API的更多信息!

2 个答案:

答案 0 :(得分:2)

一切正常,您将异步注入Google+ javascript客户端。完成此操作后,它会调用

gapi.client.load('plus', 'v1');

gapi.client.load有3个参数,第3个参数是加载Google+ API时调用的回调。

由于您没有指定回调,因此无需执行任何操作。

请参阅samples,他们定义makeRequest回调:

gapi.client.load('urlshortener', 'v1', makeRequest);

function makeRequest() {
  var request = gapi.client.urlshortener.url.get({
    'shortUrl': 'http://goo.gl/fbsS'
  });
  request.execute(function(response) {
    appendResults(response.longUrl);
  });
}

所以你想做类似的事情:

gapi.client.load('plus', 'v1', onGapiLoaded);

function onGapiLoaded() {
  // now you can request Google+ api
}

更具体地说,Google+ API samples举例说明了你在onGapiLoaded回调中可以拥有的内容:

// Returns a request object which can be executed (as below) or batched
var request = gapi.client.METHOD_NAME(PARAMETERS_OBJECT);
request.execute(callback);

示例:您可以使用以下方法向Google+ API发送搜索请求:

var request = gapi.client.plus.activities.search({'query': 'Google+', 'orderBy': 'best'});
request.execute(function(resp) { console.log(resp); });

答案 1 :(得分:1)

仅仅因为谷歌的API有时会很痛苦,这里是一个使用promise而不是回调的例子。 (即使API名称无效,我也无法使用load方法触发错误,因此我省略了该函数。)

对于上下文,这是在单独的JS文件中的Knockout.js ViewModel中。 ko.applyBindings调用是在主HTML页面内进行的,使用gapi的依赖注入将其保持在适当的范围内。 {init}函数中调用authenticate()方法,并在回调中嵌套client.load()来处理“未经过身份验证”的错误。

function myVM(gapi) {
    var _gapi = gapi;
    var self = this;

    self.authenticate = function() {
        console.log("Loading Google API...");
        _gapi.load('auth', function(param) {
            console.log("Authenticating...");
            _gapi.auth.authorize({
                client_id: '1234',
                immediate: false, /* Needs to be false for initial authorization. Setting to true will prevent the subsequent popups. */
                response_type: 'token',
                scope: 'https://www.googleapis.com/auth/content'
            }, function (token) {
                if (token.access_token) {
                    console.log('Authorized!');
                    self.authorized(true);
                    _gapi.client.load('content', 'v2').then(function() {
                        // Do stuff
                    });
                } else {
                    console.log('Authorization failed!');
                    self.authorized(false);
                }
            });
        });
    }
}