使用AngularJS从NodeJS服务器返回JSONP

时间:2016-08-03 10:05:08

标签: angularjs node.js express jsonp nginfinitescroll

我正在尝试在我的应用上实施ngInfiniteScroll - Loading Remote Data

演示工作正常&我成功获得了Reddit API,但无法让我的列表工作。

我成功点击200服务器响应&可以在开发工具中查看我的数据。这些答案得到了一些帮助1& 2但我仍然不完全确定该怎么做。

编辑(参见角度工厂编辑):

此回调现在正在运作,$http即将成功,但我现在正在Cannot read property 'length' of undefined

Angular Factory:

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

  // Edit - I changed this var from
  // var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&jsonp=JSON_CALLBACK";
  // to
  var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&callback=JSON_CALLBACK";

  $http.jsonp(url)
    .success(function(data) {
      console.log(data);
      var items = 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));
  console.log('Reddit.prototype');
};

NodeJS路线:

app.get('/list', function (req, res) {

  Found.find(function (err, post) {
    if ( err ) {
      res.send( err );
    }
    res.jsonp( post );
  });

});

1 个答案:

答案 0 :(得分:2)

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

  // Edit - I changed this var from
  // var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&jsonp=JSON_CALLBACK";
  // to
  var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&callback=JSON_CALLBACK";

  $http.jsonp(url)
    .success(function(data) {
      console.log(data);
      var items = data;
      for (var i = 0; i < items.length; i++) {
        this.items.push(items[i]);
      }
      this.after = "t3_" + this.items[this.items.length - 1].id;
      this.busy = false;
    }.bind(this));
  console.log('Reddit.prototype');
};

应该修复它!