- 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.
推薦閱讀
- 基于粒計算模型的圖像處理
- 在最好的年紀學Python:小學生趣味編程
- Python語言程序設(shè)計
- Amazon S3 Cookbook
- 軟件架構(gòu):Python語言實現(xiàn)
- Java Web開發(fā)詳解
- Mastering Xamarin.Forms(Second Edition)
- Python爬蟲、數(shù)據(jù)分析與可視化:工具詳解與案例實戰(zhàn)
- Red Hat Enterprise Linux Troubleshooting Guide
- SQL Server 2008 R2數(shù)據(jù)庫技術(shù)及應(yīng)用(第3版)
- Python編程:從入門到實踐(第3版)
- Java Web從入門到精通(第2版)
- Greenplum構(gòu)建實時數(shù)據(jù)倉庫實踐
- Node.js應(yīng)用開發(fā)
- 輕松學Scratch 3.0 少兒編程(全彩)