【问题标题】:Can't get data out of service in angularjs无法在 angularjs 中使数据停止服务
【发布时间】:2017-11-16 15:51:05
【问题描述】:

我正在使用一项服务来在 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
    });
  };
});

我真的不知道我做错了什么..

【问题讨论】:

    标签: angularjs callback angularjs-service


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答,这让我明白了我对回调函数知之甚少。我已经完成了我的作业,现在可以开始工作了!
    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    相关资源
    最近更新 更多