Reputation: 93
Hope someone can clarify something for me. What I am doing right now, working with Angular 1.4.6:
I create a service
'use strict';
angular.module('App')
.factory('processingService', ['$http',
function ($http) {
var settings = 'Settings/GetSettings';
var getSettings = function()
{
return $http.get(settings)
.then(function(response)
{
return response.data;
});
};
return {
getSettings: getSettings
};
}
]);
And use/inject that in my controller.
'use strict';
angular.module('App')
.controller('appController', [
'$scope','appService',
function ($scope, appService) {
var onSettings = function (data) {
if (data.hasOwnProperty('Settings')) {
//Code handling Settings
}
};
var onSettingsError = function()
{
//Handle Errors
$scope.showLoader = false;
};
appService.getSettings()
.then(onSettings, onSettingsError);
}]);
I started a little bit playing around with angular2 beta and found the following example on http.get
getRandomQuote() {
this.http.get('http://localhost:3001/api/random-quote')
.map(res => res.text())
.subscribe(
data => this.randomQuote = data,
err => this.logError(err),
() => console.log('Random Quote Complete')
);
}
logError(err) {
console.error('There was an error: ' + err);
}
I build some other methods and tested a bit around and googled a lot, but could not find anything similar in creating a service with angular2 beta and typescript the way I was doing till now. Is it even necessary to do it that way. Or is this not the way it is done now with Angular2 beta?
Thank you in advance.
Upvotes: 3
Views: 1730
Reputation: 202176
You can simply return an observable object (what the http.get
method returns) from your your service, i.e. a class with the Injectable
annotation:
@Injectable()
export class CompanyService {
constructor(http:Http) {
this.http = http;
}
getRandomQuote() {
return this.http.get('http://localhost:3001/api/random-quote')
.map(res => res.json());
}
}
Within your component, you can then inject this service and call the method that actually executes the HTTP request. To get the result, just use the subscribe
method:
export class CompanyList implements OnInit {
public companies: Company[];
constructor(private service: CompanyService) {
this.service = service;
}
logError(err) {
}
ngOnInit() {
this.service.getRandomQuote().subscribe(
data => this.randomQuote = data,
err => this.logError(err),
() => console.log('Random Quote Complete')
);
}
}
You could have more details at this address: How to Consume Http Component efficiently in a service in angular 2 beta?.
Hope it will help you, Thierry
Upvotes: 2
Reputation: 31600
Services in angular 2 are just TypeScript classes decorated with the @Injectable().
The service could look like this:
import {Injectable, Inject, EventEmitter} from 'angular2/core';
import {Http, Response} from 'angular2/http';
@Injectable() // annotated class that can be injected in other components
export class ProcessingService {
// inject the http service (configured in the global injector)
constructor(@Inject(Http) private http :Http) {
}
// the service method returning an event emmiter (instead of promises)
public getSettings():EventEmitter<string> {
let emmiter = new EventEmitter<string>(true);
// call the method and subscribe to the event emmiter
this.http.get('Settings/GetSettings').subscribe((value: Response) => {
emmiter.emit('called');
});
return emmiter;
}
}
Then you can use dependency injection to insert the service in a component, like this:
import {Component, Inject } from 'angular2/core';
// import our service
import {ProcessingService} from './services/processing-service/processing-service';
@Component({
selector: 'http-search-params-app',
providers: [],
templateUrl: 'app/http-search-params.html',
pipes: [],
bindings:[ProcessingService] // tell the component injector to inject our service
})
export class HttpWorkApp {
workDone = [];
constructor(private processingService: ProcessingService) {}
// call the sevice
public doWork() {
this.processingService.getSettings().subscribe((value :string) =>{
this.workDone.push(value);
});
}
}
The template for that component:
<div>
<button (click)="doWork()">Call HTTP Service</button>
<div *ngFor="#workItem of workDone">{{workItem}}</div>
</div>
You also need to configure the global inject to allow for the injection of the Http service.
import {bootstrap} from 'angular2/platform/browser';
import {HttpWorkApp} from './app/http-search-params';
import {HTTP_PROVIDERS} from 'angular2/http';
bootstrap(HttpWorkApp, [HTTP_PROVIDERS]);
Upvotes: 0