javascript - "Uncaught TypeError: Cannot read property 'people' of undefined " - Stack Overflo

I am trying to use the Plus API to sign a user in. I get the following error in the console:Uncaught Ty

I am trying to use the Plus API to sign a user in. I get the following error in the console:

Uncaught TypeError: Cannot read property 'people' of undefined

This is my logic for loading and getting profile info:

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;
    });
  }
}

and this is how I am loading the script:

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

I apologize if this is an noob question but I hope learn more about Javascript and using the G+ API!

I am trying to use the Plus API to sign a user in. I get the following error in the console:

Uncaught TypeError: Cannot read property 'people' of undefined

This is my logic for loading and getting profile info:

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;
    });
  }
}

and this is how I am loading the script:

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

I apologize if this is an noob question but I hope learn more about Javascript and using the G+ API!

Share edited May 25, 2014 at 23:08 elclanrs 94.2k21 gold badges137 silver badges171 bronze badges asked May 25, 2014 at 23:03 Isiah LIsiah L 4875 silver badges21 bronze badges 6
  • That error is saying that gapi.client.plus doesn't exist. – elclanrs Commented May 25, 2014 at 23:05
  • @elclanrs Yes, I realized that but I don't understand why it isnt loaded? Thanks for your help! – Isiah L Commented May 25, 2014 at 23:07
  • 1 you never call loadGApi() after you declare it. Why is it being declared inside jQuery 'ready`? – charlietfl Commented May 25, 2014 at 23:09
  • Not sure, haven't used G+ API but something tells me that this is an async issue, and that you should be using a callback somewhere... But I could be wrong, maybe somebody else can help. – elclanrs Commented May 25, 2014 at 23:10
  • @charlietfl Hmmm. I guess it dosnt need to be in the 'ready' but it is called in when the Google API is loaded in right here 'po.src = 'plus.google./js/client:plusone.js?onload=loadGApi';' It is passed as a URL argument as the documentation. ALso I appreciate your help – Isiah L Commented May 25, 2014 at 23:11
 |  Show 1 more ment

2 Answers 2

Reset to default 2

Everything works, your inject asynchronously the Google+ javascript client. When this is donem it calls

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

but gapi.client.load takes 3 parameters, the 3rd one being the callback called when the Google+ API is loaded.

Since you didn't specify a callback, nothing is done.

See the samples, they define the makeRequest callback:

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

and

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

So you want to do something like:

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

and

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

More specifically the Google+ API samples give an example of what you can have in the onGapiLoaded callback:

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

Example: you can send a search request to the Google+ API using the following method:

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

Just because Google's APIs can be a pain sometimes, here's an example using a promise instead of a callback. (I'm not able to trigger an error with the load method, even with an invalid API name, so I omitted that function.)

For context, this was inside a Knockout.js ViewModel in a separate JS file. The ko.applyBindings call is made inside the main HTML page, using dependency injection for the gapi to keep it in the proper scope. The authenticate() method is called from within an init function, and I nested the client.load() inside the callback to deal with "not authenticated" errors.

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./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);
                }
            });
        });
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744820381a4595579.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信