Can';在angularjs中无法从服务中获取数据

Can';在angularjs中无法从服务中获取数据,angularjs,callback,angularjs-service,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

我使用服务在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
    });
  };
});
我真的不知道我做错了什么。

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);
      }
    });
  };
});

谢谢你的回答,这让我明白了我对回调函数知之甚少。我已经做了作业,现在开始工作了!