javascript AngularJS - 对 Facebook API 的异步调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16115105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:19:10  来源:igfitidea点击:

AngularJS - Asynchronous call to Facebook API

javascriptangularjs

提问by Deividi Cavarzan

I'am trying to call a Facebook API with AngularJS.

我正在尝试使用 AngularJS 调用 Facebook API。

The problem is that all calls from FB API is Asynchronous, so I need to know when my query on facebook is avaliable to use in agularjs.

问题是来自 FB API 的所有调用都是异步的,所以我需要知道我在 facebook 上的查询何时可以在 agularjs 中使用。

For this, I call this method in my controller:

为此,我在控制器中调用此方法:

Facebook.getLoginStatus();

Facebook.getLoginStatus();

which Facebook is my service, defined as:

哪个 Facebook 是我的服务,定义为:

app.factory('Facebook', function() {

    getLoginStatus: function() {

        FB.getLoginStatus(function(stsResp) {
            console.log(stsResp);
            if(stsResp.authResponse) {
                // User is already logged in
                return true;
            } else {
                // User is not logged in.
                return false;
            }
        });
    }

}

app.factory('Facebook', function() {

    getLoginStatus: function() {

        FB.getLoginStatus(function(stsResp) {
            console.log(stsResp);
            if(stsResp.authResponse) {
                // User is already logged in
                return true;
            } else {
                // User is not logged in.
                return false;
            }
        });
    }

}

What I want in this case is to check if user is logged. If true, I'll show some options, otherwise, I'll show the Login button.

在这种情况下,我想要的是检查用户是否已登录。如果为真,我将显示一些选项,否则,我将显示登录按钮。

I've already try to use $q.defer() functions, promises, factorys to watch response data, everything. But anything works as I want. I've checked some development examples based on Egghead.ioexamples, but I think that I'm not fully understand asynchronous calls in angularjs.

我已经尝试使用 $q.defer() 函数、promise、工厂来观察响应数据,一切。但是任何事情都可以按我的意愿工作。我已经检查了一些基于Egghead.io示例的开发示例,但我认为我没有完全理解 angularjs 中的异步调用。

Thanks in advance.

提前致谢。

回答by karlgold

Here's a full basic working example of wrapping the Facebook API in an Angular service:

这是将 Facebook API 包装在 Angular 服务中的完整基本工作示例:

http://plnkr.co/edit/0GRLdWPJOzGFY14irxLT?p=preview

http://plnkr.co/edit/0GRLdWPJOzGFY14irxLT?p=preview

See also my answer to this question (which has some partial examples of Angular-FB integration):

另请参阅我对此问题的回答(其中包含一些 Angular-FB 集成的部分示例):

AngularJS : Where to use promises?

AngularJS:在哪里使用承诺?

回答by orcaman

if you want to have all fb code in a slightly more angularish style, consider doing something like encapsulating the FB classes in a provider. FB is one rare example where the provider pattern is actually nice to use (to setup your app ID on the config section).

如果您想让所有 fb 代码的风格稍显棱角分明,请考虑执行诸如将 FB 类封装在提供程序中之类的操作。FB 是一个罕见的例子,其中提供程序模式实际上很好用(在配置部分设置您的应用程序 ID)。

here's an example of an angular facebook provider with basic login functionality and generic method for making graph api calls:

这是具有基本登录功能和用于进行图形 API 调用的通用方法的 angular facebook 提供程序的示例:

app.provider('facebook', function() {
  var fbReady = false
  this.appID = 'Default';

  function fbInit(appID) {
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));  
    window.fbAsyncInit = function() {
     FB.init({
      appId      : appID,
      cookie     : true,  
      xfbml      : true,  
      version    : 'v2.0' 
    });
     fbReady = true;
   }   
 }

 this.setAppID = function(appID) {
  this.appID = appID;
};

this.$get = function() {
  var appID = this.appID;
  var self = this;
  fbInit(appID);

  return {
    graph : function(path, cb) {
      FB.api(path, function(response) {
        cb(response);
      });
    },
    getAuth: function() {
      return self.auth;
    },
    getLoginStatus: function(cb) {
      if (!fbReady) {
        setTimeout(function() { 
          self.$get()['getLoginStatus'](cb);
        } , 100);
        console.log('fb not ready');
        return;
      }
      FB.getLoginStatus(function(response) {
        cb(response);
      });
    },
    login: function(cb) {
      if (!fbReady) {
        self.$get()['login'](cb);
        console.log('fb not ready');
        return;
      }
      FB.login(function(response) {
        if (response.authResponse) {
          self.auth = response.authResponse;
          cb(self.auth);
        } else {
          console.log('Facebook login failed', response);
        }
      }, {"scope" : "manage_notifications"});

    },
    logout: function() {
      FB.logout(function(response) {
        if (response) {
          self.auth = null;
        } else {
          console.log('Facebook logout failed.', response);
        }

      });
    }
  }
}
});

later when you want to use it, simply set your app's ID in the config section:

稍后当您想使用它时,只需在配置部分设置您的应用程序 ID:

app.config(function(facebookProvider){
 facebookProvider.setAppID('<your_app_id>');
})

inject it to a controller:

将其注入控制器:

.controller('MainCtrl', function ($scope, facebook) {

and then perform some calls in a controller/run section:

然后在控制器/运行部分执行一些调用:

facebook.graph('/me/notifications', onNotificationsGotten);

回答by Ciul

I wrote this module angularjs-facebook as a provider, such that on config you configure your app id and then you can use facebook asynchronous calls. There are also methods to listen on controllers.

我写了这个模块 angularjs-facebook 作为提供者,这样你就可以在配置中配置你的应用程序 ID,然后你就可以使用 facebook 异步调用。还有一些方法可以监听控制器。

https://github.com/ciul/angularjs-facebook

https://github.com/ciul/angularjs-facebook

回答by James Morris

Heres a good example of making asynchronous http requests with the iTunes API. It should help you figure out how to do it with the Facebook API as well.

这是使用 iTunes API 发出异步 http 请求的一个很好的例子。它也应该可以帮助您弄清楚如何使用 Facebook API 来做到这一点。

Asynchronous HTTP requests in Angular JS

Angular JS 中的异步 HTTP 请求