Angular 2 - HTTP Services

HTTP Services

app.module.ts

  • Lines 3 and 4: You have to import the FormsModule and HttpModule libraries.
  • Line 8: Import your data service here or it won't work.
  • Lines 17 and 18: @ngModule decorator: In the imports array you also have to list the FormsModule and the HttpModule. (Components get added in the declarations array).
  • Line 20: Any services you create you have to list here in the providers array.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { StocksComponent } from './components/stocks/stocks.component';
import { DataService } from './services/data.service';

@NgModule({
  declarations: [
    AppComponent,
    StocksComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }


data.service.ts

  • Lines 1 - 3: You have to import the Injectable, Http and map libraries. Injectable because the service has to be injected into the constructor and map because the results from the actual HTTP call come back raw and you need to map the results to JSON format.
  • Line 8: Decalare your HTTP call as a HTTP type. It's an OOP thing....
  • Lines 10 and 11: Define your method to call from your components; in this case the url is for a GET request and the results need to be mapped to JSON using an arrow function.

data.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataService{

  constructor(public http:Http){}

  getStocks(){
    return this.http.get('http://api.iextrading.com/1.0/stock/LITE/quote').map(res => res.json());
  }
}



yourComponent.component.ts (stocks.component.ts)

  • Line 2: Import your data service file.
  • Line 11: Declare an empty variable for your return call from your service.
  • Line 13: Inject your data service into your constructor call.
  • Line 15: Angular is using an Observable to subscribe to your data service, and the resulting arrow function method assigns the result to a variable you can use for display in your template via interpolation (line 7).

stocks.component.ts

import { Component } from '@angular/core';
import { DataService } from '../../services/data.service';

@Component({
  selector: 'app-stocks',
  template: `

Hello from Stocks Component

Todays closing price for {{ stock.symbol }} is {{stock.close}}. ` }) export class StocksComponent { stock:any[]; constructor(public dataService:DataService) { this.dataService.getStocks().subscribe(stock => { //console.log(stock); this.stock = stock; }); } }

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/angular2/angular-2-http-services/