angular factory里怎么写回调函数让controller能拿到factory里面的值

题目描述

angular factory里怎么写回调函数让controller能拿到factory里面的值

题目来源及自己的思路

我用了$scope.Reddit因为是异步加载的拿不到里面的值求大佬解答

相关代码

var myApp = angular.module('myApp', ['infinite-scroll']);

myApp.controller('DemoController', function($scope, Reddit) {
  $scope.reddit = new Reddit();
    //感谢大佬解答怎么拿到factory里的items中的数据
});

// Reddit constructor function to encapsulate HTTP and pagination logic
myApp.factory('Reddit', function($http) {
  var Reddit = function() {
    this.items = [];
    this.busy = false;
    this.after = '';
  };

  Reddit.prototype.nextPage = function() {
    if (this.busy) return;
    this.busy = true;

    var url = "http://api.reddit.com/hot?after=" + this.after + "&jsonp=JSON_CALLBACK";
    $http.jsonp(url).success(function(data) {
      var items = data.data.children;
      for (var i = 0; i < items.length; i++) {
        this.items.push(items[i].data);
      }
      this.after = "t3_" + this.items[this.items.length - 1].id;
      this.busy = false;
    }.bind(this));
  };

  return Reddit;
});

你期待的结果是什么?实际看到的错误信息又是什么?

拿到factory里的数据

阅读 2.3k
2 个回答
var myApp = angular.module('myApp', ['infinite-scroll']);

myApp.controller('DemoController', function($scope, Reddit) {
var afterParam = "xxxxx",
self = this;
    this.busy = true;
   Reddit.nextPage(afterParam).then(
    function(afterid){
        //success
        self.busy = false;
        console.log(afterid) //result from factory
    },function(){
        //error
        self.busy = false;
        //error handler
    })
});

// Reddit constructor function to encapsulate HTTP and pagination logic
myApp.factory('Reddit', function($http) {
  var Reddit = {};
  Reddit.nextPage = function(after) {


    var url = "http://api.reddit.com/hot?after=" + after + "&jsonp=JSON_CALLBACK";
    return $http.jsonp(url).success(function(data) {
      var items = data.data.children;
      
      return "t3_" + items[items.length - 1].data.id;
    });
  };

  return Reddit;
});

首先你的Service要注入$sce 

其次修改你的url包装为$sce.trustAsResourceUrl(url)

然后修改你的nextPage方法 

return $http.jsonp($sce.trustAsResourceUrl(url)).then(function(data) {
        let items = data.data.data.children;
        for (let i = 0; i < items.length; i++) {
            this.items.push(items[i].data);
        }
        this.after = 't3_' + this.items[this.items.length - 1].id;
        this.busy = false;
        return items;
    }.bind(this));
    

最后测试调用

let reddit = new Reddit();
reddit.nextPage().then(function(items) {
    console.log('items:::', items);
});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进