Ich habe einen Dienst in separaten JS-Datei, dieser Dienst ist wie OOP-Klasse, die "Methoden" zum Laden der erforderlichen Daten aus dem Internet enthält.Q.all.then wartet nicht auf die Fertigstellung
nenne ich will diese ‚Methoden‘ und die Daten in meinem Haupt-JS-Datei erhalten, eigentlich möchte ich Daten von drei Typen laden und Kraftfluss JS zu warten, bis die Daten abgerufen werden, hier ist mein Code:
services.js
// My 'Class' to load data from the web server
myApp.factory("LoadData", ["_gl", function (_gl) {
return {
GetUsers: function ($http) {
$http({
method: 'POST',
url: 'http://localhost/dgis/ps/select.php',
data: { "action": "GetUsers" }
}).then(function successCallback(response) {
// Save the response JSON object to my global objects
_gl.myUsers = response.data;
}, function errorCallback(response) {
console.log("GetUsersError:" + response);
});
},
GetObGroups: function ($http) {
$http({
method: 'POST',
url: 'http://localhost/dgis/ps/select.php',
data: { "action": "GetObGroups" }
}).then(function successCallback(response) {
// Save the response JSON object to my global objects
// This code fills array because it iterates through it
angular.forEach(response.data, function (value, key) {
_gl.myObGroups.push(value)
});
}, function errorCallback(response) {
console.log("GetObGroups:" + response);
});
},
GetObjects: function ($http) {
$http({
method: 'POST',
url: 'http://localhost/dgis/ps/select.php',
data: { "action": "GetObjects" }
}).then(function successCallback(response) {
_gl.myObjects = response.data;
}, function errorCallback(response) {
console.log("GetObjectsError:" + response);
});
}
}
}]);
// My global variables
myApp.factory('_gl', function() {
return {
myUsers: [],
myOrganisations: [],
myObGroups: [],
myObjects: []
}
});
script.js
Q.all([LoadData.GetUsers($http), LoadData.GetObGroups($http), LoadData.GetObjects($http)]).then(function() {
console.log(_gl.myUsers);
console.log(_gl.myObGroups);
console.log(_gl.myObjects);
});
Das Problem ist, die Q.all
wird nicht warten, bis alle HTTP-Anfrage die Daten erhalten, wertet Anrufe in then
, bevor es passiert. Sicher, ich könnte einen Timer verwenden und nur eine Sekunde warten, aber ich möchte einen besseren Weg, das zu tun, bitte teilen Sie mit Ihrem Wissen.
Und noch eine Sache, wenn ich forEach
in then
meiner Methoden Get, dann Arrays füllen in Ordnung, aber andere Arrays sind leer und ich möchte wissen, warum es passiert.
Vielen Dank.
Machen [MCVE] (http://stackoverflow.com/help/mcve) –