ප්‍රධාන පිටුවට

මොඩියුලය 8: HTTP & APIs

නූතන web යෙදුම් බාහිර API (Application Programming Interfaces) සමඟ සන්නිවේදනය කරයි. Angular හි `HttpClient` භාවිතයෙන් HTTP ඉල්ලීම් (requests) යවන ආකාරය සහ ලැබෙන ප්‍රතිචාර (responses) කළමනාකරණය කරන ආකාරය ඉගෙන ගනිමු.

HttpClient සමඟ HTTP ඉල්ලීම් කිරීම

Angular හි `HttpClient` service එක මගින් backend server එකක් සමඟ සන්නිවේදනය කිරීමට සරල ක්‍රමයක් සපයයි. මෙය භාවිතා කිරීමට, පළමුව `app.module.ts` ගොනුවට `HttpClientModule` import කළ යුතුය.

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http'; // <-- Import here

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule // <-- Add to imports
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

ඉන්පසු, ඕනෑම service එකක හෝ component එකක constructor එකට `HttpClient` inject කර HTTP methods (GET, POST, PUT, DELETE) භාවිතා කළ හැක.

Observables සහ RxJS මූලික කරුණු

`HttpClient` methods මගින් දත්ත කෙලින්ම ලබා දෙන්නේ නැත. ඒ වෙනුවට, ඒවා Observable එකක් return කරයි.

Observable යනු කාලයත් සමඟ පැමිණිය හැකි දත්ත ප්‍රවාහයක් (stream of data) වේ. API එකෙන් දත්ත ලැබෙන තුරු බලා සිටීමට මෙය අපට ඉඩ සලසයි. දත්ත ලැබුණු විට, අපට දැනුම් දෙනු ලැබේ.

Observable එකකින් දත්ත ලබාගැනීමට නම්, එයට subscribe කළ යුතුය. දත්ත පැමිණි විට subscribe එක තුළ ඇති function එක ක්‍රියාත්මක වේ.

// post.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class PostService {
  private apiUrl = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getPosts() {
    return this.http.get(this.apiUrl); // Returns an Observable
  }
}
// posts.component.ts
import { Component, OnInit } from '@angular/core';
import { PostService } from './post.service';

@Component({ ... })
export class PostsComponent implements OnInit {
  posts: any;

  constructor(private postService: PostService) { }

  ngOnInit() {
    this.postService.getPosts()
      .subscribe(response => {
        this.posts = response;
        console.log(this.posts);
      });
  }
}

RxJS යනු Observables සමඟ වැඩ කිරීමට පහසුකම් සලසන library එකකි. දත්ත ප්‍රවාහයන් හැසිරවීමට `map`, `filter`, `catchError` වැනි ප්‍රබල operators එය සපයයි.

Interceptors (අතරමැදියන්)

HTTP Interceptor යනු යෙදුමෙන් පිටතට යන සෑම HTTP request එකක්ම සහ යෙදුමට ඇතුළුවන සෑම HTTP response එකක්ම අතරට මැදිහත් විය හැකි service එකකි.

මෙය ඉතා ප්‍රයෝජනවත් වේ, මන්ද:

  • සෑම request එකකටම authentication token එකක් වැනි header එකක් එක් කිරීමට.
  • දෝෂ (errors) මධ්‍යගතව හැසිරවීමට (centralized error handling).
  • Request සහ response ලොග් කිරීමට (logging).
  • Loading spinner එකක් පෙන්වීමට/සැඟවීමට.

Interceptor එකක් යනු `HttpInterceptor` interface එක implement කරන සාමාන්‍ය service එකකි.

// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const authToken = 'YOUR_AUTH_TOKEN';
    
    // Clone the request and add the authorization header
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${authToken}`)
    });

    // Pass the cloned request instead of the original
    return next.handle(authReq);
  }
}
« පෙර (මොඩියුලය 7) ඊළඟ (මොඩියුලය 9) »