2017-11-16 6 views
1

Ich verwende einen Dienst, um Daten zwischen verschiedenen Instanzen eines AngularJS-Controllers zu übertragen. Ich weiß, dass dies nicht der beste Weg ist, aber es passt zu meinem Fall. Das Problem ist, dass ich keine Daten aus diesem Service abrufen kann.In angularjs können keine Daten außer Betrieb gesetzt werden.

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

Ich kann wirklich nicht herausfinden, was mache ich falsch ..

Antwort

1

SnapshotService.init() keine Parameter übernehmen - das heißt die anonyme Funktion, die Sie mit dem SnapshotService.init() Anruf passieren in in TileController nichts tut.


Was Sie tun müssen, um die Parameter auf die init Funktionsdefinition hinzufügen und sie dann in dem Code nennen:

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

Danke für Ihre Antwort, es gab mich zu verstehen, wie wenig ich wusste von Rückruffunktionen. Ich habe meine Hausaufgaben gemacht und es jetzt zur Arbeit gebracht! –

Verwandte Themen