Angular HTTP: GET 404 response from server

I have created this HTTP request method:

public isExisting(id: string): Observable<boolean> {
    const createURL = () => map((userId: string) => this.createIdURL(userId));
    const createResponse = () => map(() => true);
    const handleErrorResponse = <T>() => catchError<T, boolean>((error: Response) => this.handleError(error));
    const sendRequest = () => switchMap((url: string) => this.authHttp.head(url));

    return Observable.of(id)
        .pipe(
            createURL(),
            sendRequest(),
            createResponse(),
            handleErrorResponse()
        );
}

Now, I want to manage the response in the following cases:

  1. If the response is a 404 error, I should return Observable.of(false)
  2. Otherwise, I should return Observable.throw(error).

Any suggestions?

Answer №1

I believe I've grasped your requirements accurately. The issue you are encountering with the catchError method should include the status code. This will enable you to handle it effectively.

Although I did not conduct an in-depth search, I vaguely remember utilizing HttpErrorResponse instead of Response to gain more insight into the HTTP response.

A few months back, I implemented something similar to the following:

const onErrorGetDetails = <T>() => catchError<T, boolean>((error: HttpErrorResponse) => {
    if (error.status === 404) {
        return of(false)
    }
    return throwError(error)

Answer №2

In order to achieve this, you must configure an option known as

{observe: 'response'} 

This option allows you to access the response status of an http call. Your http call should look like this:

  makeCall(): Observable<any> {
        return this.http.get('uri', {observe: 'response'});
      } 

When subscribing, simply check the error status. You can also check the error status without subscribing by using the map or catchError operators and examining the Response.

Below is an example of how I applied this concept to JWT validation:

return this.auth.validateJwt().pipe(
        map( (response) => {
          if (response.status === 200) {
            return true;
          }
        }),
        catchError((err: Response) => {
          this.handleError('authentication');
          if (err.status === 200) {
            return of(true);
          }

          return of(false);
        }),
        first()
      ); 

In this implementation, I check if the response code is 200, which means the server returned something. However, if the server is offline or if I input a wrong URL in the code, I handle the error because there is still a response even without a body.

For more information, refer to the Angular documentation: https://angular.io/guide/http#reading-the-full-response

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

What steps can I take to eliminate the overload error that occurs when I extend the Request object in Express?

I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me. EDIT: I am currently using Passport.js and JWT ...

The Angular 2 http request seems to be failing to reach the web api's get method when using a string parameter overload

Issue at hand is that the initial Get method gets triggered by this particular HTTP request: http://localhost:56690/api/testelements/?name=aeg One would anticipate the second (string overload) method to be invoked due to the presence of a string parameter ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

The collaboration between an object literal declaration and an object instantiated through a constructor function

If I declare let bar: Bar; and set it to initialFooConfig;, is bar still considered as type Bar and an object, or does it become an object in literal notation? If the assignment can be done both ways (assuming initialFooConfig is not a constant), what set ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

Using wildcard in Angular app for MQTT observation

My curiosity lies in MQTT wildcards and how they function, specifically while utilizing the mosqitto broker. Let's say I have around 1-2k topics. In my frontend, I am observing them with a single-level wildcard using ngx-mqtt. Will there be a separat ...

Switching between various conditions

Here is a sample of my component: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'myApp-component', templateUrl: './myApp.component.html', styleUrls: ['./myApp.component.scss'] }) ex ...

Effortlessly adding custom classes in Angular 2 with a breeze

Imagine having a growing Angular2 typescript solution with numerous small classes and objects. Following the best practice, each class is placed in its own file. However, manipulating these objects leads to long lists of imports like: import {Object1} f ...

Enhancing CKEditor functionality with Angular 2 for improved textarea usage

Check out this Plunker example: https://plnkr.co/edit/aUBtpe?p=preview When using CKEditor, the value of the content variable does not update when changes are made to the textarea. It remains the same as the original page.content variable that was obtaine ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...

JSDoc encounters issues when processing *.js files that are produced from *.ts files

I am currently working on creating documentation for a straightforward typescript class: export class Address { /** * @param street { string } - excluding building number * @param city { string } - abbreviations like "LA" are acceptable ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

An easy guide on incorporating npm packages into a typescript project

In my TypeScript project, I am encountering an issue with the following imports: import * as schedule from "node-schedule"; import * as ACTIONS from "../../../actions"; The second import resolves successfully, but the first one does no ...

Error Handler: Unable to retrieve the error object when utilized with a promise

I'm currently working on an angular application with a custom error handler implementation. One interesting point to note is that when you have a custom error handler and use an observable with http without catching errors using a catch block, like i ...

Tips for accessing a Literal type in TypeScript instead of a Union type

I recently developed a function to generate dynamic elements. However, I encountered an issue where instead of returning the precise type of the element, it was producing a union of various <HTMLElementTagNameMap> types. function createCustomElement( ...

How to extract component prop types in Vue 3 with typescript for reusability in other parts of your application

When you specify the props under the "props:" key of a Vue component, Vue can already automatically determine their types, which is quite convenient. However, I am wondering if there is an utility type in Vue that can be used to extract the props' ty ...

Transferring data between components in React by passing parameters through Links

When calling another component like <A x={y}/>, we can then access props.x inside component A. However, in the case of calling EditCertificate, the id needs to be passed to the component. I am using a Link here and struggling to pass the id successf ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Tips for setting default values on Angular environments

For my Angular application, I have multiple environment files: environment.ts environment.dev.ts environment.prod.ts Instead of duplicating default variables in each file, I want to have them shared across all environments. For example, if I define a va ...

Utilize multiple validators.patterns within a single value for enhanced data validation

I need to implement two different patterns for the formControlName='value' based on the type selected. If type is 'A', I want to use the valuePattern, and if type is 'B', I want to use the uname pattern. This is my HTML code: ...