Services in Angular

In real time Angular UI component should focus on presenting data and delegate data access to a service. Services in angular could be singleton and lazy instantiated.services. Singleton service gets created when angular app components need them using $injector. Lets jump directly and create a sample service. We are using public api to get the stock quote and display on UI.

code will looks like stockservice.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class StockService {

  constructor(private http: Http) { }
  getStockPriceLive() {
    return this.http.get('https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=MSFT,FB,AAPL&apikey=demo')
      .map(res => res.json());
  }
}

servicesamplecomponent.ts file looks like:

import { Component, OnInit } from '@angular/core';
import { StockService } from '../stock.service';

@Component({
  selector: 'app-service-sample',
  templateUrl: './service-sample.component.html',
  styleUrls: ['./service-sample.component.css']
})
export class ServiceSampleComponent implements OnInit {
 stock: any[];
  constructor(private stockService: StockService) { }

  ngOnInit() {
    this.getLiveStockPrice();
  }

  getLiveStockPrice() {
    this.stockService.getStockPriceLive().subscribe((result) => {
      console.log(result['Stock Quotes']);
      this.stock = result['Stock Quotes'];

    });
  }
}

Now display on UI:
Screen Shot 2018-03-11 at 2.07.57 PM
As we can see we created a stock service for loosely-coupled communication between classes.The StockService injected into a component is created with another component, Service sample.HttpClient is Angular’s mechanism for communicating with a remote server over HTTP. HttpClient.get returns the body of the response as an untyped JSON object by default. Next sample we will try to make API call that returns an observable collection of objects.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s