Using a service

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.

How to do it...

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.

  1. In our 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']);
    

How it works...

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.

See also

  • For more information about Futures, refer to Chapter 8, Working with Futures, Tasks, and Isolates
  • For more details about JSON HTTP requests, refer to the Downloading a file recipe in Chapter 6, Working with Files and Streams
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset