1

I'm using a service in order to pass data between different instances of an AngularJS controller. I know that this is not the best way to do it but it's the way that fits my case. The problem is that I cannot get data out of that Service.

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

I really can't figure out what I'm doing wrong..

1 Answer 1

1

SnapshotService.init() doesn't take any parameters - meaning the anonymous function you pass in with the SnapshotService.init() call in TileController does nothing.


What you need to do is add the parameter to the init function definition and then call it in the code:

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);
      }
    });
  };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, it made me understand how little I knew about callback functions. I have done my homework and got it to work now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.