This is the second post in a series covering the new Ionic Generators in Ionic 2.0. In the first post, we discussed generating pages, let’s focus now on generating some services to consume some JSON data via an http request.
~/Development/testing/MyIonic2App$ ionic g injectable MyDataService
√ Create www/app/my-data-service/my-data-service.js
The basic blueprint of the generated service is as follows:
Generated Data Service
1234567891011121314151617181920212223
import{Injectable}from'angular2/angular2';import{Http}from'angular2/http';@Injectable()exportclassMyDataService{constructor(http:Http){this.http=http;this.data=null;}retrieveData(){//Here, we're going to get a JSON data file, use the `map` call to parse json// and finally subscribe to the observable and set our data//to the value it provides once the http request is complete.this.http.get('path/to/data.json').map(res=>res.json()).subscribe(data=>{this.data=data;},error=>{console.log('Error with http.get: ',error);});}}
Wiring it in to be used
Adjust www/app/app.js to import the data service, as well as provide it for all of its components:
We’ll use the tabs starter dashboard page to pull data.
Let’s modify www/app/dash/dash.ts – adding an import for MyDataService, adding MyDataService to the constructore as an injected dependency, and finally adding the call to retrieveData in the constructore method.