无法在angularjs中获取服务数据

时间:2017-11-16 15:51:06

标签: angularjs callback angularjs-service

我正在使用服务,以便在AngularJS控制器的不同实例之间传递数据。我知道这不是最好的方法,但它适合我的情况。问题是我无法从该服务中获取数据。

var app = angular.module('MovieApp', ['ngResource']);

app.factory('factMovies', function($resource) { //this returns some movies from MongoDB
  return $resource('/movies');
});

app.service('SnapshotService', function(factMovies) {
  //this is used to pass data to different instances of the same controller
  //omitted getters/setters
  this.snapshots = [];

  this.init = function() {
    var ctrl = this;
    var resp = factMovies.query({}, function() {
      if (resp.error) {
        console.log(resp.error)
      } else {
        tempDataset = []
        //do stuff and put the results in tempDataset
        ctrl.snapshots.push(tempDataset);
        console.log(tempDataset); //prints fine
        return tempDataset;
      }
    });
  };
});

app.controller('TileController', function(SnapshotService) {
  this.dataset = [];
  this.filters = [];
  this.init = function() {
    var ctrl = this;
    var data = SnapshotService.init(function() {
      console.log(ctrl.data); //doesn't even get to the callback function
    });
  };
});

我真的无法弄清楚我做错了什么..

1 个答案:

答案 0 :(得分:1)

SnapshotService.init()不接受任何参数 - 这意味着您通过SnapshotService.init()中的TileController调用传入的匿名函数不会执行任何操作。

您需要做的是将参数添加到init函数定义中,然后在代码中调用它:

app.service('SnapshotService', function(factMovies) {
  //this is used to pass data to different instances of the same controller
  //omitted getters/setters
  this.snapshots = [];

  this.init = function(cb) {
    var ctrl = this;
    var resp = factMovies.query({}, function() {
      if (resp.error) {
        console.log(resp.error)
      } else {
        tempDataset = []
        //do stuff and put the results in tempDataset
        ctrl.snapshots.push(tempDataset);
        console.log(tempDataset); //prints fine
        cb(ctrl.snapshots);
      }
    });
  };
});