What I'm trying to do is take the array of objects that is returned to me from the API and create a new object and then add that object to the employees list.
I am getting the correct results from the API its just creating a new object from the results and attaching that object to the employeesList array.
var employeesList = [];
this.getEmployees = function () {
$http.get("https://randomuser.me/api/?nat=us&results=100&inc=name,location")
.then(function(response) {
employees = response.data.results;
employees.map(employee => {
return [
employee.employeeName = employee.name.first + ' ' + employee.name.last,
employee.employeeStreet = employee.location.street.number + ' ' + employee.location.street.name,
employee.employeeCity = employee.location.city,
employee.employeeState = employee.location.state,
employee.employeeZipCode = employee.location.postcode,
];
});
});
return employeesList;
};
The expected results are an array of employee objects however I am getting an empty array before I even return the employeesList.
UPDATE I have the initial problem working however it makes it difficult when I am trying to add or delete an employee.
this.addEmployee = function (employee) {
var employeesList = this.getEmployees();
employeesList.push(employee);
var str = JSON.stringify(employeesList);
localStorage.setItem("Employees", str);
};
this.removeEmployee = function (employee) {
var employeesList = this.getEmployees();
employeesList.splice(employeesList.indexOf(employee), 1);
var str = JSON.stringify(employeesList);
localStorage.setItem("Employees", str);
};
$httpservice does not wait for the data to arrive from the server. It holds the function in the.thenblock and invokes that function later. Functions that depend on the$httpservice can never return data. They can only return promises.