To add a service to an Angular 2 app, I need to do three things:
- Create a model of the data – name.ts
export class Name { id: number; field1: string; field2: number; } - Create the name.service.ts – This typically uses Injectable, Headers, Http, Response, imports the model, and uses toPromise.
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Name } from './name'; import 'rxjs/add/operator/toPromise'; @Injectable() export class NameService { private nameUrl = 'http://host.com/url.json'; private headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' }); constructor( private http: Http) {} getNames(): Promise<Name[]> { return this.http.get(this.nameURL, { headers: this.headers } ) .toPromise() .then(response => response.json() as Name[]) .catch(this.handleError); } getName(id: number): Promise<Name> { return this.http.get(this.nameUrl + '/' + id, { headers: this.headers }) .toPromise() .then(response => response.json() as Name) .catch(this.handleError); } update(name: Name): Promise<Name> { const url = `${this.nameURL}/${name.id}`; return this.http .put(url, name, {headers: this.headers}) .toPromise() .then(() => name) .catch(this.handleError); } create(name: string): Promise<Name> { return this.http .post(this.nameUrl, JSON.stringify({thingtoupdate: thingtoupdatevalue}), {headers: this.headers}) .toPromise() .then(res => res.json().data) .catch(this.handleError); } delete(id: number): Promise<void> { const url = `${this.nameURL}/${id}`; return this.http.delete(url, {headers: this.headers}) .toPromise() .then(() => null) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } } - Update app.module.ts – Add the service to the import list and add the service to the providers in the app.module.ts
import './rxjs-extensions'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { DashboardComponent } from './dashboard.component'; import { HeroComponent } from './heroes.component'; import { HeroDetailComponent } from './hero-detail.component'; import { HeroService } from './hero.service'; import { HeroSearchComponent } from './hero-search.component'; import { NameService } from './name.service'; import { routing } from './app.routing'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, routing ], declarations: [ AppComponent, HeroComponent, HeroDetailComponent, HeroSearchComponent, DashboardComponent ], providers: [ HeroService, NameService ], bootstrap: [ AppComponent ] }) export class AppModule {}
This code is taken from the Angular2 Tour of Heroes github repository and generalized. Using Angular2 release 2.0.1:
"dependencies": {
"@angular/common": "~2.0.1",
"@angular/compiler": "~2.0.1",
"@angular/core": "~2.0.1",
"@angular/forms": "~2.0.1",
"@angular/http": "~2.0.1",
"@angular/platform-browser": "~2.0.1",
"@angular/platform-browser-dynamic": "~2.0.1",
"@angular/router": "~3.0.1",
"@angular/upgrade": "~2.0.1",
"angular-in-memory-web-api": "~0.1.1",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"reflect-metadata": "^0.1.8",
"rxjs": "5.0.0-beta.12",
"systemjs": "0.19.39",
"tabletop": "^1.4.3",
"zone.js": "^0.6.25"
}