AngularJS调用回调函数

时间:2019-02-06 20:00:36

标签: angularjs rest angularjs-scope angularjs-service angularjs-http

我想调用一个回调函数,但由于调用错误而无法获取数据。

我尝试过:

//function with callback
filterList: function(type, cb) {

 if (type == 'all') {
  var resource = infoboxApi.resource1().query();
 } else if (type == 'group') {
  var resource = infoboxApi.resource2().query();
 }

 resource.$promise.then(function(events) {
  var eventContainer = [];
  angular.forEach(events, function(event) {                  
   eventContainer.push({
    id: event.id,
    title: event.title
   })
  });
  cb(eventContainer);
 });

 return wrapSaveHandlers(resource);
 }



//call i tried
var newSources = [];
filterList('all', function(result) {
 newSources = result;
});

我希望newSources包含数据,但如果我这样称呼它,则为空。

有人知道怎么称呼它吗?

1 个答案:

答案 0 :(得分:1)

避免在基于承诺的API中使用回调。而是使用return语句:

 //function without callback
 filterList: function(type) {
     var resource;       
     if (type == 'all') {
         resource = infoboxApi.resource1().query();
     } else if (type == 'group') {
         resource = infoboxApi.resource2().query();
     };

     //RETURN the promise
     return resource.$promise.then(function(events) {
         var eventContainer = [];
         angular.forEach(events, function(event) {                  
             eventContainer.push({
                 id: event.id,
                 title: event.title
             })
         });
         //RETURN the data
         return eventContainer;
     });
 }

然后从返回的promise中提取数据:

var newSources = [];
filterList('all').then(function(result) {
    newSources = result;
});

.then方法返回一个新的诺言,该诺言通过successCallback errorCallback的返回值来解决或拒绝(除非该值是一个诺言,在这种情况下,它将被解决并使用promise chaining在该承诺中解析的值。