我试图在ng-repeat中调用我的Facebook服务,但不知何故,Facebook API调用限制很快就会受到影响。
我有这样的服务:
angular.module('core').factory('Facebook', ['$q',
function ($q) {
return {
getMutualFriends: function (fbUserId) {
var deferred = $q.defer();
var path = "/" + fbUserId;
FB.api(
path,
{
'fields': 'context.fields(mutual_friends)'
},
function (response) {
if (!response || response.error) {
deferred.reject('Error occured');
} else {
deferred.resolve(response);
}
}
);
return deferred.promise;
}
};
}
]);
在我的控制器中,我有一个调用服务的函数:
$scope.getMutualFriendsCount = function (fbUserId) {
if (fbUserId === '' || fbUserId === undefined) return 0;
Facebook.getMutualFriends(fbUserId)
.then(function (response) {
// untested response
return response.context['mutual_friends']['summary']['total_count'];
});
}
在我的模板中,我有data-ng-repeat="profile in profiles"
,对于每个配置文件,我尝试绑定结果data-ng-bind=getMutualFriends(profile.fbId)
。
该服务设法与FB服务器进行通信,直到我开始注意到循环期间有太多的呼叫并且呼叫限制非常快(在我的开发机器上仅在20个配置文件的页面内刷新1或2次) )。有没有人知道如何更好地设计获得多个ID的共同朋友的方法?
答案 0 :(得分:1)
你不应该调用一个从被监视的表达式发出HTTP请求的函数,无论它是ng-bind
还是等价的{{ }}
。此表达式和随后的HTTP调用将在每个摘要周期调用 - 显然不是您期望或需要的。
相反,获取您需要的数据并将其存储在每个profile
中,并从ng-repeat
中访问该值。
另外,根据上面的评论,您应该考虑批量调用Facebook。创建一个单独的服务来处理所有这些复杂性,并向控制器公开一个简单的API。