- Hybrid Mobile Development with Ionic
- Gaurav Saini
- 251字
- 2021-07-02 23:53:50
Services match providers
Services and Factory are important parts of Angular 1x where we communicate with a remote server for data. We used to define APIs call inside factory functions that controllers calls for fetching data from the servers:
// Factory method in Angular 1x
angular.module('wedding.services', [])
// DI of $http for HTTP calls to servers
// $q for promises
.factory('CategoryService', function ($http, $q) {
var catalog = {};
catalog.getCategories = function () {
// here we will call APIs
}
})
Now you will see how we have migrated our code to Angular 4 providers. The same getCategories() method that was inside factory in Angular 1, will now be moved inside the CategoryData() class in Angular 4:
// Provider in Angular 4
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class CategoryData {
constructor(private http: Http) {}
getCategories() {
return new Promise(resolve => {
// We're using Angular Http provider
to request the data,
// then on the response it'll map the
JSON data to a parsed JS object.
// Next we process the data and
resolve the promise with the new
data.
this.http.get('www.veloice.com/data.json').subscribe(res
=> {
// we've got back the raw data, now
generate the core schedule data
// and save the data for later
reference
this.data = this.processData(res.json());
resolve(this.data);
});
});
}
}
You will notice that the Provider class has a @Injectable decorator. This decorator lets Angular 4 know that the specific class can be used with the dependency injector.