The following step is to read the data from a JSON file, which we will use in this recipe. Angular has a built-in core functionality called the HTTP Service to make HTTP requests to a server. In our example, the job data has been serialized to the JSON format in the file jobs.json
, and we will make an HTTP request to the web server to get this data. You can follow along with the code in the project angular_service
.
The change we make in this recipe is nearly transparent to the user; the web page stays the same, but because making an HTTP request is asynchronous, we will work with a Future and must provide a message, such as "Loading data…"
, as long as the request is being executed.
JobListingController
controller class, libjob_listing.dart
, we define a new variable of the type Http: final Http _http;
. The constructor now becomes the following:JobListingController(this._http) {
_loadData();
}
The bulk of the change takes place in its _loadData()
method, as shown in the following code:
static const String LOADING_MESSAGE = "Loading jobs listing..."; static const String ERROR_MESSAGE = "Sorry! The jobs database cannot be reached."; String message = LOADING_MESSAGE; void _loadData() { jobsLoaded = false; _http.get('jobs.json') .then((HttpResponse response) { jobs = response.data.map((d) => new Job.fromJson(d)).toList(); jobsLoaded = true; for (var job in jobs) { // extract companies: companies.add(job.company); } }) .catchError((e) { print(e); message = ERROR_MESSAGE; }); }
In the class Job
we have a new named constructor, as follows:
Job.fromJson(Map<String, dynamic> json) : this(json['type'], json['salary'], json['company'], DateTime.parse(json['posted']), json['skills'], json['info']);
In step 1, we see that Angular uses dependency injection when instantiating the controller to supply it with an Http
object. Step 2 shows how the get
method from the Http
service is used to make a GET
request and to fetch data from the server (here the data is local, but it could be fetched from a remote site). This method returns a Future <HttpResponse>
when the request is fulfilled. That's why we have to use a .then
construct to register a callback function and a .catchError
to handle exceptions. In the callback function, we have the data in response.data
. With map
, we call for each job as a JSON string. The named constructor fromJson
in the class Job
from step 3 to transform it into a Job
object. Finally, a list is made with all job data, which is bound to the view in the same way as in the previous recipes.