I stumbled upon this IONIC app's services.js file and found an example using a hardcoded object called "employees." Instead of using the hardcoded object, I wanted to use a JSON file. However, my attempt to make this change did not work as expected. I believe sharing the solution could be beneficial for others who are new to Ionic development.
Here is the initial services.js code:
angular.module('directory.services', [])
.factory('EmployeeService', function($q) {
var employees = [
{"id": 1, "firstName": "James", "lastName": "King", "managerId": 0, ... },
// Employee data continues...
];
// The use of promises in this service may seem unnecessary with in-memory data,
// but it adds flexibility for future modifications. For instance, switching
// to a JSON service fetching data from a remote server can be done seamlessly without
// altering any existing modules since the API is already asynchronous.
return {
findAll: function() {
var deferred = $q.defer();
deferred.resolve(employees);
return deferred.promise;
},
// Other functions omitted for brevity
};
});
Below is my attempt to replace the hardcoded object with data fetched from a JSON file:
angular.module('directory.services', [])
.factory('EmployeeService', function($q,$http) {
$http.get("http://localhost:3000/api/users").then(function(response){
myObject = response.data;
});
var employees = myObject;
// Similar explanation about using promises for flexibility
return {
findAll: function() {
var deferred = $q.defer();
deferred.resolve(employees);
return deferred.promise;
},
// Other functions omitted for brevity
};
});
Despite my efforts, the code does not function properly.