diff --git a/apps/rxjs/38-catch-error/src/app/app.component.ts b/apps/rxjs/38-catch-error/src/app/app.component.ts index 65e177567..b148507a6 100644 --- a/apps/rxjs/38-catch-error/src/app/app.component.ts +++ b/apps/rxjs/38-catch-error/src/app/app.component.ts @@ -1,12 +1,12 @@ -import { CommonModule } from '@angular/common'; -import { HttpClient } from '@angular/common/http'; +import { JsonPipe } from '@angular/common'; import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormsModule } from '@angular/forms'; import { Subject, concatMap, map } from 'rxjs'; +import { FetchDataService } from './fetching-data.service'; @Component({ - imports: [CommonModule, FormsModule], + imports: [FormsModule, JsonPipe], selector: 'app-root', template: `
@@ -34,15 +34,13 @@ export class AppComponent implements OnInit { response: unknown; private destroyRef = inject(DestroyRef); - private http = inject(HttpClient); + private fetchingDataService = inject(FetchDataService); ngOnInit() { this.submit$ .pipe( map(() => this.input), - concatMap((value) => - this.http.get(`https://jsonplaceholder.typicode.com/${value}/1`), - ), + concatMap((value) => this.fetchingDataService.fetchData(value)), takeUntilDestroyed(this.destroyRef), ) .subscribe({ diff --git a/apps/rxjs/38-catch-error/src/app/fetching-data.service.ts b/apps/rxjs/38-catch-error/src/app/fetching-data.service.ts new file mode 100644 index 000000000..9c3ea72b9 --- /dev/null +++ b/apps/rxjs/38-catch-error/src/app/fetching-data.service.ts @@ -0,0 +1,23 @@ +import { HttpClient } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; +import { catchError, Observable, of } from 'rxjs'; + +@Injectable({ providedIn: 'root' }) +export class FetchDataService { + private readonly http = inject(HttpClient); + private readonly url = 'https://jsonplaceholder.typicode.com'; + + fetchData(value: string): Observable { + return this.http.get(`${this.url}/${value}/1`).pipe( + catchError((err) => { + const errorMsg = + err.error instanceof ErrorEvent + ? `Client-side error: ${err.error.message}` + : `Server-side error (${err.status}): ${err.message}`; + + console.warn(errorMsg); + return of({ error: errorMsg }); + }), + ); + } +}