Dealing with mistakes in an Angular service

I've been grappling with error handling in Angular. I attempted to handle errors within a service, but I'm uncertain if that's the correct approach.

@Injectable({
  providedIn: 'root',
})
export class CaseListService {
  public constructor(private httpClient: HttpClient, private router: Router) {}

  private get baseUrl() {
    return environment.apiBaseUrl || '/api';
  }

  public getCaseList(): Observable<CaseListModel[]> {
    return this.httpClient.get(this.baseUrl + '/cases').pipe(
      map((response) => response as Array<CaseListModel>),
      catchError((err: any) => {
        if (err.status) {
          console.log('Service temporarily unavailable' + err.status);
          this.router.navigate(['/unavailable']);
        }
        return throwError(err.statusText);
      })
    );
  }
}

Here is my component.ts where I am utilizing the service:

@Component({
  selector: 'app-case-list',
  templateUrl: './case-list.component.html',
  styleUrls: ['./case-list.component.css'],
})
export class CaseListComponent implements OnInit {
  title = 'List of cases';
  readonly CaseList$: Observable<CaseListModel[]>;

  constructor(private caseListService: CaseListService) {
    this.CaseList$ = caseListService.getCaseList();
  }

  displayedColumns: string[] = ['ID', 'name', 'actions'];
  dataSource = this.caseListService.getCaseList();

  ngOnInit(): void {}
}

When I disabled the backend and tested it, all I got was a frontend display with empty data. The redirection didn't work, and there were no logs in the console either. What could be the issue here?

Answer №1

For detailed information on how to handle errors with Angular's HTTP client, please refer to the official documentation.

It is important to note that the status field in HttpErrorResponse is not always present and can be undefined, which may explain why the functions console.log and navigate are not being called.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

MyApp is encountering issues resolving all parameters

I'm encountering an issue that none of the other similar questions have been able to help me solve. Can anyone offer assistance? I've already attempted removing parameters one by one, but I'm still stuck. Can't resolve all parameters f ...

Can someone please explain the significance of these three lines in the Angular file App module.ts?

This pertains to an Angular file called appmodule.ts <pre> import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UploadModule } from '@progress/kendo-angular-upload&ap ...

"Seamlessly incorporating an Angular project into a React environment

Seeking advice on integrating a React website project with an Angular widget project. Does anyone have suggestions for combining the two together seamlessly? ...

The risk of a race condition could arise when working with nested switchMaps in ngr

I am currently working on an Angular 9 application that heavily relies on observables. In a specific component, I have the following requirements: Retrieve all companies to access certain information. Fetch all responses and link additional company detai ...

Using RxJS with Angular to intercept the valueChanges of a FormControl prior to subscribing

I decided to create a new observable using the values emitted by the FormControls.valueChanges observable. This creation of the observable takes place within the ngOnInit method in the following manner: ngOnInit(): void { this.myObservable$ = combine ...

calculating the dynamic height of a document from top to bottom using Angular

Is there a way to dynamically calculate the height of each page from top to bottom in Angular? The syntax that works in JavaScript seems to give an error in Angular. console.log( (document.height !== undefined) ? document.height : document.body.offsetHeigh ...

Angular's counterpart to IWebProxy

When using C#, I am able to: public static IWebProxy GetWebProxy() { var proxyUrl = Environment.GetEnvironmentVariable("HTTPS_PROXY"); if (!string.IsNullOrEmpty(proxyUrl)) { var proxy = new WebProxy { Address = new Ur ...

Encountering a Geolocation API issue during the troubleshooting of an Angular application on

Currently, I'm in the process of developing an angular application that utilizes the GeoLocation API to retrieve user location. To achieve this, I make use of the navigator.geolocation.getCurrentPosition() function. Surprisingly, everything works perf ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

displaying a pair of inputs next to each other

Is it possible to display two input fields side by side? I am using Angular's matInput forms, but struggling to position the second input next to the first. What I would like to achieve is to have "input1 , input2" on the same line. Here is my code: ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Utilize a custom Angular2 validator to gain entry to a specific service

For accessing my custom http service from within a static method, consider the following example: import {Control} from 'angular2/common'; import {HttpService} from './http.service'; class UsernameValidator { static usernameExist( ...

I'm having difficulty updating the Angular CLI version

I am currently running Angular CLI version 7.1.4 and I have been attempting to update to the latest version. However, each time I try to update, I encounter a multitude of errors. I have attempted using the command ng update @angular/core @angular/cli b ...

Should we use fakeAsync() or done() to handle asynchronous tasks

When creating an Angular test with Jest and dealing with asynchronous operations, do you have a preference for how to handle it? it('', fakeAsync(() => { // test code here })); or would you rather use something like it('' ...

Comparing the Calculation of CSS Selector Specificity: Class versus Elements [archived]

Closed. This question requires additional information for debugging purposes. It is not currently accepting answers. ...

When attempting to append a script element and the operation fails due to lack of authorization, which error is typically thrown

I am trying to handle a particular failure in this JavaScript code: var script = $wnd.document.createElement('script'); script.setAttribute('src', url); script.setAttribute('type', 'text/javascript'); When the URL ...

Tips for assigning dynamic #id(*ngFor) and retrieving its value in Angular2

In my HTML file, I have the following code snippet: <tr *ngFor="let package of packages"> <td *ngFor="let coverage of coverages"> <input type="hidden" #dynamicID [value]="coverage.id"> <-- Include an identifier with the vari ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...