Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions apps/rxjs/38-catch-error/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -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: `
<div class="form-container">
Expand Down Expand Up @@ -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({
Expand Down
23 changes: 23 additions & 0 deletions apps/rxjs/38-catch-error/src/app/fetching-data.service.ts
Original file line number Diff line number Diff line change
@@ -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<unknown> {
return this.http.get<unknown>(`${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 });
}),
);
}
}