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

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.

主站蜘蛛池模板: 准格尔旗| 麻江县| 随州市| 二连浩特市| 宣威市| 广元市| 通渭县| 花莲县| 台北县| 临洮县| 岑溪市| 嘉鱼县| 仙游县| 河东区| 布尔津县| 东海县| 丰原市| 象州县| 炎陵县| 手机| 来宾市| 舒城县| 祥云县| 浑源县| 东海县| 南乐县| 巴东县| 大关县| 民和| 黄山市| 丽江市| 高陵县| 彰化市| 靖边县| 华宁县| 治县。| 周宁县| 理塘县| 泾川县| 武鸣县| 孝昌县|