官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 株洲县| 外汇| 顺义区| 安义县| 宜兰县| 新宁县| 东乌珠穆沁旗| 连南| 兴文县| 农安县| 安仁县| 柳州市| 化隆| 五莲县| 麻江县| 麻阳| 定边县| 文山县| 略阳县| 洮南市| 肇东市| 商丘市| 辽阳县| 辽源市| 涿州市| 泰来县| 虎林市| 定州市| 行唐县| 武清区| 连州市| 呼图壁县| 南皮县| 襄垣县| 渝中区| 宜春市| 如皋市| 安顺市| 永城市| 黔西| 清水河县|