In the current implementation of the application, the view (app.js) is tightly coupled to the data access strategy used to retrieve data. In this unit, we create a Data Service that hides the specific data access strategy behind a generic API.
In the /js
directory, create a new file named employee-service.js
In employee-service.js
, import the request
module
import request from './request';
Create a findAll()
method implemented as follows:
export let findAll = () => {
return request({url:"employees.json"})
.then(data => data = JSON.parse(data))
}
In app.js
, remove the request
import and import the employee-service
module instead:
import * as service from "./employee-service";
Replace the call to request()
with a call to findAll()
in the employee-service
module:
service.findAll()
.then(employees => {
let html = "";
employees.forEach(function(employee){
html += `<div>
<img src='${employee.picture}'/>
<div>
${employee.firstName} ${employee.lastName}
<p>${employee.phone}</p>
</div>
</div>`;
});
document.getElementById("list").innerHTML = html;
})
.catch(error => console.log(error)
);
Build the app:
npm run webpack
Make sure your local http server is started, open a browser and access http://localhost:8080.
The final code for this step is available in this branch.