【问题标题】:AngularJS call callback functionAngularJS调用回调函数
【发布时间】:2019-06-30 21:04:50
【问题描述】:

我想调用一个回调函数,但是因为我的调用错误,我无法获取数据。

我试过了:

//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】:

    避免在基于 Promise 的 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 方法返回一个新的 Promise,它通过 successCallbackerrorCallback 的返回值被解析或拒绝(除非该值是一个 Promise,在这种情况下,它使用已解析的值解析在那个承诺中使用promise chaining

    【讨论】:

    • ty 为这段代码,但如果我查看 newSources 在调用 filterList 后它仍然是空的
    • 使用标准调试技术来确定数据丢失的位置。插入console.log 语句。查看开发者控制台中的网络标签。
    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多