מדריך Angular – עבודה עם RxJS באנגולר

מדריך Angular – עבודה עם RxJS באנגולר

במאמר הקודם למדנו על ניהול State מתקדם עם NgRx, היום נלמד על RxJs

RxJS (Reactive Extensions for JavaScript) הוא ספרייה רבת עוצמה לניהול פעולות אסינכרוניות באפליקציות אנגולר. באמצעות RxJS ניתן לעבוד עם streams (זרמים) ולנהל בצורה יעילה את הפעולות האסינכרוניות והאירועים באפליקציה.

התקנת RxJS

כדי להשתמש ב-RxJS באפליקציית אנגולר, עליך להתקין את הספרייה. ניתן לעשות זאת באמצעות npm:

npm install rxjs

הבנת הבסיס של RxJS

ב-RxJS ישנם מספר מושגים בסיסיים שחשוב להכיר:

Observable: זהו מקור המידע, אשר יכול לשדר נתונים לאורך זמן.

Observer: זהו הצופה, שמאזין לנתונים הנשלחים מה-Observable.

Operators: אלו פונקציות המשמשות לשינוי נתונים העוברים דרך Observable.

יצירת Observable

כדי ליצור Observable, ניתן להשתמש בפונקציה new Observable של RxJS:

import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.next('World');
  subscriber.complete();
});

observable.subscribe({
  next(x) { console.log('Received: ' + x); },
  complete() { console.log('Completed'); }
});

שימוש באופרטורים

אופרטורים ב-RxJS מאפשרים לבצע פעולות שונות על הנתונים העוברים דרך Observable. להלן דוגמה לשימוש באופרטור map:

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

const numbers = of(1, 2, 3, 4, 5);
const squaredNumbers = numbers.pipe(
  map(num => num * num)
);

squaredNumbers.subscribe(x => console.log(x));

שימוש ב-Subject

Subject הוא סוג מיוחד של Observable המאפשר גם שליחה וגם קבלה של נתונים. להלן דוגמה לשימוש ב-Subject:

import { Subject } from 'rxjs';

const subject = new Subject();

subject.subscribe({
  next: (v) => console.log('ObserverA: ' + v)
});

subject.subscribe({
  next: (v) => console.log('ObserverB: ' + v)
});

subject.next('Hello');
subject.next('World');

שילוב RxJS באפליקציית אנגולר

כדי להשתמש ב-RxJS באנגולר, יש לייבא את הספרייה ולהשתמש בה בשירותים או בקומפוננטות. להלן דוגמה לשימוש ב-RxJS בשירות אנגולר:

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) {}

  getData(): Observable {
    return this.http.get('https://api.example.com/data').pipe(
      map(response => response.data)
    );
  }
}

שימוש ב-RxJS בקומפוננטה

כדי להשתמש בשירות עם RxJS בקומפוננטה, יש לייבא את השירות ולהשתמש בו בקומפוננטה:

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

@Component({
  selector: 'app-data',
  template: `
    {{ item }}
  `
})
export class DataComponent implements OnInit {
  data: any[];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      this.data = data;
    });
  }
}

שימוש ב-RxJS עם טפסים

אפשר לשלב RxJS עם טפסים באנגולר כדי לנהל את נתוני הטופס בצורה יעילה. לדוגמה, נניח שאנחנו רוצים לאמת שדה טקסט בטופס:

<form [formGroup]="form">
  <input formControlName="username" (input)="onInput()" />
  <div *ngIf="errorMessage">{{ errorMessage }}</div>
</form>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { debounceTime, switchMap } from 'rxjs/operators';
import { DataService } from './data.service';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html'
})
export class FormComponent implements OnInit {
  form: FormGroup;
  errorMessage: string;

  constructor(private fb: FormBuilder, private dataService: DataService) {}

  ngOnInit() {
    this.form = this.fb.group({
      username: ['']
    });
  }

  onInput() {
    this.form.get('username').valueChanges.pipe(
      debounceTime(300),
      switchMap(value => this.dataService.checkUsername(value))
    ).subscribe(
      valid => this.errorMessage = valid ? '' : 'Username is taken',
      error => this.errorMessage = 'Error occurred'
    );
  }
}

סיכום

RxJS היא ספרייה רבת עוצמה לניהול פעולות אסינכרוניות באנגולר. באמצעות RxJS ניתן לנהל בקלות זרמי נתונים ולהגיב לשינויים בצורה יעילה. בעזרת RxJS ניתן לשפר את ביצועי האפליקציה ולנהל נתונים בצורה מסודרת וברורה. אני ממליץ להתנסות ב-RxJS ולראות כיצד היא יכולה לשפר את האפליקציות שלכם.

אם אתם מעוניינים ללמוד בצורה מעמיקה יותר אתם מוזמנים להתייעץ איתנו על קורס אנגולר.

במאמר הבא נלמד על שימוש ב-HTTP Client לאינטראקציה עם API חיצוניים – הישארו איתנו 🙂

שתפו את הפוסט

דילוג לתוכן