Angular Services and Dependency Injection: creating and injecting services, using HttpClient to call REST APIs; Observables with RxJS

Angular services hold shared logic and are supplied to components by dependency injection, and HttpClient calls REST APIs returning Observables (from RxJS) that you subscribe to for the data.

12 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Connecting the front-end to real data

FestConnect's Angular UI is built, but it shows fake events. Time to connect it to the REAL back-end, the MongoDB-backed API from Unit 1. That means making HTTP requests from Angular.

Angular does this cleanly: a service holds the data-fetching logic, dependency injection supplies it to any component, and HttpClient makes the request. But the result is not a plain value or even a Promise: it is an Observable, from a library called RxJS. Understanding Observables is the last piece of the Angular puzzle, and this lesson ties the whole unit together: front-end talking to back-end.

Theory

Services fetch, DI supplies

Data-fetching logic belongs in a service, not scattered across components. A service is an @Injectable class; you inject Angular's HttpClient into it and call REST endpoints:

  • http.get(url) reads, http.post(url, body) creates, plus put/delete

Any component that needs events declares the service in its constructor (dependency injection), and Angular supplies the shared instance. So one EventService serves the whole app: the DI benefit from the concepts lesson, now doing real work. The component asks the service, the service asks the API, the data flows back. Keeping HTTP in a service (not in components) is the clean, testable Angular pattern.

Practical

A service with HttpClient, and a component subscribing

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EventService {
  constructor(private http: HttpClient) {}   // DI supplies HttpClient

  getEvents(): Observable<any[]> {
    return this.http.get<any[]>('/api/events');   // returns an Observable
  }
}

// A component uses the service and SUBSCRIBES to the Observable:
export class EventsComponent implements OnInit {
  events: any[] = [];
  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().subscribe(data => {
      this.events = data;    // runs when the response arrives
    });
  }
}

Theory

Observables: streams you subscribe to

http.get() returns an Observable, not the data itself. An Observable (from RxJS) is a STREAM of asynchronous values that you must subscribe to:

this.eventService.getEvents().subscribe(data => this.events = data);

The subscribe callback runs WHEN the response arrives. Key properties:

  • lazy: nothing happens until you subscribe (unlike a Promise, which runs immediately)
  • can emit over time (multiple values), not just once
  • transformable with operators (map, filter) and cancellable

Compared to React's fetch(...).then(data => ...) (a Promise), Angular's Observable is more powerful, built for streams of values, but the everyday use is the same: request, then handle the data when it comes. (The async pipe can even subscribe for you in the template.)

Quiz

HttpClient's http.get('/api/events') returns an Observable. How do you get the actual data out of it?

  1. The data is returned immediately from http.get()
  2. You SUBSCRIBE to the Observable: .subscribe(data => ...), and the callback runs when the response arrives
  3. You read Observable.value directly
  4. Observables cannot carry HTTP responses
Show the answer

You SUBSCRIBE to the Observable: .subscribe(data => ...), and the callback runs when the response arrives

An Observable is a lazy stream: http.get() does not return the data directly, it returns an Observable that does nothing until you SUBSCRIBE. Calling .subscribe(data => ...) both TRIGGERS the request and gives you a callback that runs when the response arrives with the data. Option A treats it like a synchronous return, which it is not (HTTP is asynchronous). Option C invents a .value property; you get values through subscription (or the async pipe), not by reading a property. Option D is false: Observables are exactly how Angular delivers HTTP responses. Remember: Observables are lazy, subscribe to trigger and receive. (In React the parallel was fetch().then(); the Observable is the more powerful streaming cousin.)

Think first

Observable vs Promise: why does Angular use Observables?

React fetched data with a Promise (fetch().then()). Angular uses Observables. What does an Observable offer that a Promise does not? Then tap.

Show the answer

A Promise resolves ONCE with a single value and runs immediately when created. An Observable is more capable: (1) it can emit MULTIPLE values over time (a stream, e.g. live updates, keystrokes, websocket messages), not just one; (2) it is LAZY, nothing happens until you subscribe, so you control when it runs; (3) it is CANCELLABLE, you can unsubscribe to stop it (important for cleanup, e.g. in ngOnDestroy); and (4) it composes with RxJS OPERATORS (map, filter, debounce) to transform the stream declaratively. For a one-off HTTP GET, a Promise would suffice, and Observables can feel like overkill, but Angular standardises on Observables because the SAME abstraction handles simple requests AND complex streams uniformly. For everyday fetching, you use it much like a Promise (subscribe instead of then); the extra power is there when you need it.

Watch out

Service and Observable traps

Forgetting to subscribe: an Observable is lazy; without subscribe (or the async pipe) the HTTP request never fires.

HTTP logic in components: put it in a SERVICE and inject the service; keep components lean.

Not unsubscribing: long-lived subscriptions can leak; unsubscribe in ngOnDestroy (or use the async pipe, which unsubscribes for you).

Treating Observable like a Promise's return: you cannot read its value synchronously; handle it in subscribe.

Missing HttpClientModule/provideHttpClient: HttpClient must be provided, or injection fails.

Theory

Unit 3 complete: the Angular stack

FestConnect now exists in TWO complete modern stacks: a React front-end and an Angular front-end, both on the MongoDB back-end. You have compared the industry's two leading frameworks first-hand: React's minimal library plus hooks, and Angular's full framework with TypeScript, DI, directives, pipes, forms and Observables. Unit 4 is different: the Indian Knowledge System mathematics topic (Lilavati), studied factually. The modern web work is done; the IKS unit stands apart.

Summary

Key takeaways

  • Services (@Injectable classes) hold reusable logic/data (like fetching events) and are supplied to components by dependency injection.
  • HttpClient makes HTTP requests to REST APIs: http.get/post/put/delete; keep HTTP logic in services, not components.
  • HttpClient returns an Observable (from RxJS), not the data directly.
  • An Observable is a lazy stream: subscribe to trigger the request and receive the data when it arrives.
  • Observables can emit over time, be transformed with operators (map, filter), and be cancelled: more powerful than a Promise.
  • Unsubscribe (in ngOnDestroy) or use the async pipe to avoid leaks; React's fetch().then() is the Promise parallel.
  • Memory hook: service + DI to share, HttpClient to call, subscribe to an Observable to get the data.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Fundamentals of Angular

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Angular Services and Dependency Injection: creating and injecting services, using HttpClient to call REST APIs; Observables with RxJS · Advance Web Designing (Major-11-01) · Gri-Learn