AngularJS调用回调函数

问题描述 投票:0回答:1

我想调用回调函数,而是因为我的电话是错的我不能获得数据。

我试过了:

//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包含数据,但它是空的,如果我这样称呼它。

任何人都知道如何调用它的正确方法?

angularjs rest angularjs-scope angularjs-service angularjs-http
1个回答
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;
     });
 }

和提取返回的承诺的数据:

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

.then方法返回一个新许其经由successCallback的返回值解决或拒绝,errorCallback(除非该值是一个承诺,在这种情况下,它与在该承诺使用promise chaining解决的值解决。

© www.soinside.com 2019 - 2024. All rights reserved.