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

Angular services shared logic hold करती हैं और dependency injection के through components को supply होती हैं, और HttpClient REST APIs call करता है जो Observables (RxJS से) return करते हैं जिन्हें आप data के लिए subscribe करते हैं।

12 min read · 9 cards · 2 checks

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


Theory

Front-End को Real Data से Connect करना

FestConnect का Angular UI बन चुका है, पर यह fake events दिखाता है। समय है इसे REAL back-end से connect करने का, Unit 1 का MongoDB-backed API। मतलब Angular से HTTP requests बनाना।

Angular इसे cleanly करता है: एक service data-fetching logic hold करती है, dependency injection इसे किसी भी component को supply करता है, और HttpClient request बनाता है। पर result एक plain value या यहाँ तक कि एक Promise नहीं है: यह एक Observable है, RxJS नाम की एक library से। Observables समझना Angular puzzle का आख़िरी piece है, और यह lesson पूरी unit साथ tie करता है: front-end back-end से बात करता हुआ।

Theory

Services Fetch करती हैं, DI Supply करता है

Data-fetching logic एक service में belong करती है, components के across scattered नहीं। एक service एक @Injectable class है; आप इसमें Angular का HttpClient inject करते हैं और REST endpoints call करते हैं:

  • http.get(url) पढ़ता है, http.post(url, body) बनाता है, plus put/delete

कोई भी component जिसे events चाहिए अपने constructor में service declare करता है (dependency injection), और Angular shared instance supply करता है। तो एक EventService पूरे app को serve करती है: concepts lesson से DI benefit, अब real work करते हुए। Component service से पूछता है, service API से पूछती है, data वापस flow करता है। HTTP को एक service में रखना (components में नहीं) clean, testable Angular pattern है।

Practical

HttpClient वाली एक Service, और Subscribe करता एक Component

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 जिन्हें आप Subscribe करते हैं

http.get() एक Observable return करता है, खुद data नहीं। एक Observable (RxJS से) asynchronous values का एक STREAM है जिसे आपको subscribe करना पड़ता है:

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

subscribe callback तब चलता है जब response आता है। Key properties:

  • lazy: कुछ नहीं होता जब तक आप subscribe न करें (एक Promise के उलट, जो तुरंत चलती है)
  • समय के साथ emit over time कर सकता है (कई values), सिर्फ़ एक बार नहीं
  • operators से (map, filter) transformable और cancellable

React के fetch(...).then(data => ...) (एक Promise) से compare करते हुए, Angular का Observable ज़्यादा powerful है, values के streams के लिए built, पर everyday इस्तेमाल same है: request कीजिए, फिर data आने पर handle कीजिए। (async pipe template में आपके लिए automatically subscribe भी कर सकता है।)

Quiz

HttpClient का http.get('/api/events') एक Observable return करता है। आप इसमें से actual data कैसे निकालते हैं?

  1. Data http.get() से तुरंत return होता है
  2. आप Observable को SUBSCRIBE करते हैं: .subscribe(data => ...), और callback तब चलता है जब response आता है
  3. आप Observable.value सीधे पढ़ते हैं
  4. Observables HTTP responses carry नहीं कर सकते
Show the answer

आप Observable को SUBSCRIBE करते हैं: .subscribe(data => ...), और callback तब चलता है जब response आता है

एक Observable एक lazy stream है: http.get() data directly return नहीं करता, यह एक Observable return करता है जो तब तक कुछ नहीं करता जब तक आप SUBSCRIBE न करें। .subscribe(data => ...) call करना request को TRIGGER करता है AND आपको एक callback देता है जो response data के साथ आने पर चलता है। Option A इसे synchronous return की तरह treat करता है, जो यह नहीं है (HTTP asynchronous है)। Option C एक .value property invent करता है; आप values subscription (या async pipe) के through पाते हैं, एक property पढ़कर नहीं। Option D false है: Observables exactly वही तरीका है जिससे Angular HTTP responses deliver करता है। याद रखिए: Observables lazy हैं, trigger और receive करने के लिए subscribe कीजिए। (React में parallel fetch().then() था; Observable इसका ज़्यादा powerful streaming cousin है।)

Think first

Observable बनाम Promise: Angular Observables क्यों इस्तेमाल करता है?

React ने Promise (fetch().then()) से data fetch किया। Angular Observables इस्तेमाल करता है। एक Observable क्या offer करता है जो एक Promise नहीं करती? फिर tap कीजिए।

Show the answer

एक Promise ONCE एक single value के साथ resolve होती है और बनते ही तुरंत चलती है। एक Observable ज़्यादा capable है: (1) यह समय के साथ MULTIPLE values emit कर सकता है (एक stream, जैसे live updates, keystrokes, websocket messages), सिर्फ़ एक नहीं; (2) यह LAZY है, कुछ नहीं होता जब तक आप subscribe न करें, तो आप control करते हैं यह कब चले; (3) यह CANCELLABLE है, आप इसे रोकने के लिए unsubscribe कर सकते हैं (cleanup के लिए important, जैसे ngOnDestroy में); और (4) यह RxJS OPERATORS (map, filter, debounce) से compose होता है stream को declaratively transform करने के लिए। एक one-off HTTP GET के लिए, एक Promise काफ़ी होती, और Observables overkill लग सकते हैं, पर Angular Observables पर standardise करता है क्योंकि SAME abstraction simple requests AND complex streams दोनों uniformly handle करता है। Everyday fetching के लिए, आप इसे Promise की तरह ही इस्तेमाल करते हैं (then की बजाय subscribe); extra power वहाँ है जब आपको चाहिए।

Watch out

Service और Observable Traps

Subscribe करना भूलना: एक Observable lazy है; subscribe (या async pipe) के बिना HTTP request कभी fire नहीं होती।

Components में HTTP Logic: इसे एक SERVICE में रखिए और service inject कीजिए; components को lean रखिए।

Unsubscribe न करना: long-lived subscriptions leak कर सकती हैं; ngOnDestroy में unsubscribe कीजिए (या async pipe इस्तेमाल कीजिए, जो आपके लिए unsubscribe करता है)।

Observable को Promise के Return की तरह Treat करना: आप इसकी value synchronously नहीं पढ़ सकते; इसे subscribe में handle कीजिए।

Missing HttpClientModule/provideHttpClient: HttpClient provided होना चाहिए, नहीं तो injection fail होता है।

Theory

Unit 3 Complete: The Angular Stack

FestConnect अब दो complete modern stacks में exist करता है: एक React front-end और एक Angular front-end, दोनों MongoDB back-end पर। आपने industry के दो leading frameworks first-hand compare किए हैं: React की minimal library plus hooks, और Angular का full framework TypeScript, DI, directives, pipes, forms और Observables के साथ। Unit 4 अलग है: Indian Knowledge System mathematics topic (Lilavati), जिसे factually पढ़ा जाता है। Modern web work हो चुका है; IKS unit अलग खड़ी है।

Summary

Key takeaways

  • Services (@Injectable classes) reusable logic/data hold करती हैं (events fetch करने जैसा) और dependency injection के through components को supply होती हैं।
  • HttpClient REST APIs को HTTP requests बनाता है: http.get/post/put/delete; HTTP logic services में रखिए, components में नहीं।
  • HttpClient एक Observable (RxJS से) return करता है, data directly नहीं।
  • एक Observable एक lazy stream है: request trigger करने और data आने पर receive करने के लिए subscribe कीजिए।
  • Observables समय के साथ emit कर सकते हैं, operators (map, filter) से transform हो सकते हैं, और cancel हो सकते हैं: एक Promise से ज़्यादा powerful।
  • Leaks से बचने के लिए unsubscribe कीजिए (ngOnDestroy में) या async pipe इस्तेमाल कीजिए; React का fetch().then() Promise parallel है।
  • Memory hook: share करने के लिए service + DI, call करने के लिए HttpClient, data पाने के लिए एक Observable को subscribe कीजिए।

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