Skip to content

Instantly share code, notes, and snippets.

@Kamilnaja
Created January 21, 2023 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kamilnaja/327812c91d0d3bcd2245ff7ad86ab39f to your computer and use it in GitHub Desktop.
Save Kamilnaja/327812c91d0d3bcd2245ff7ad86ab39f to your computer and use it in GitHub Desktop.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, Subject, takeUntil } from 'rxjs';
import { FoodService } from './food.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
destroy$ = new Subject<void>();
search = new FormControl('');
foods$ = new Subject<Object>(); // nie przypisujemy danych bezpośrednio, tylko robimy subject typu Food
loading$ = new Subject<boolean>();
constructor(private foodService: FoodService) {}
ngOnInit(): void {
this.getData(); // pobieramy dane inicjalnie
// można wydzielić to do metody listenForSearchValueChanges...
this.search.valueChanges // śledzenie wartości formularza
.pipe(
takeUntil(this.destroy$), // nasłuchiwanie tylko do momentu destroy komponentu, zapobiega wyciekowi danych
debounceTime(200) // gdy przerwa trwa 200 ms to dopiero wtedy strzał
)
.subscribe((formValue) => {
this.getData(formValue); // pobieramy dane na kazdej zmianie
});
}
private getData(searchBy?: string) {
this.loading$.next(true); // włączamy loaderek bo jest szukanie
this.foodService.searchFoods(searchBy).subscribe({ // pobierz dane z backu
next: (data) => {
this.foods$.next(data); // update danych nową wartością z backendu
},
complete: () => {
this.loading$.next(false); // niezalenie czy sukces czy błąd, wyłączamy loaderek
},
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.unsubscribe();
}
}
<div>
<input [formControl]="search" />
</div>
{{ foods$ | async | json }}
<div *ngIf="loading$ | async">Loading</div>
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class FoodService {
readonly apiURL = 'http://localhost:8080/api/';
constructor(private httpClient: HttpClient) {}
searchFoods(searchBy?: string) {
let params;
if (searchBy) {
// tworzymy paramsy
params = new HttpParams({ fromString: `name=${searchBy}` });
}
// strzał z paramsami albo bez
return this.httpClient.get(`${this.apiURL}/foods`, { params: params });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment