无法在 angularjs 中停止服务数据

Can't get data out of service in angularjs

我正在使用一项服务,以便在 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() 不接受任何参数 - 这意味着您在 TileController 中通过 SnapshotService.init() 调用传入的匿名函数什么都不做。


你需要做的是将参数添加到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);
      }
    });
  };
});