简体   繁体   中英

How to error handle and log those errors on a http get request in Angular

I have a service that gets data from a web api. I want to add error handling in there and then log those errors in the console, my code so far is:

Service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse} from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class nowService {

  serviceApiUrl: string = 'https://demo1049220.mockable.io/api/incident';

  constructor(
    private http: HttpClient,

  ) { }

  getAll(): Observable<any> {
    return this.http.get<any>(this.serviceApiUrl)
  }
}

component.ts

     constructor(private service: nowService) {

  }

  ngOnInit() {
    this.service.getAll().subscribe((data) => {
      this.loading = true;
      this.incidents = data;
      this.loading = false;
      console.log('Result - ', data);
      console.log('data is recieved');
    })
  }
}

You can use rxjs operator catchError

this.service.getAll()
.pipe(
        catchError(err => console.log(err))
)
.subscribe((data) => {
      this.loading = true;
      this.incidents = data;
      this.loading = false;
      console.log('Result - ', data);
      console.log('data is received');
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM