What is the best way to detect errors in Angular 2?

I am making a server call as shown below:

In the case of success,

STATUS---200

{error_code: 0, status: "success", results: [,…], message: "Album successfully found."}

If there is a failure, STATUS---401

 Login credentials are incorrect.

To handle this, I have implemented the following code:

 Upon sending a POST request to this.serverUrl+'login' with loginForm.value and headers,
        .subscribe(response => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        }) 
  }

However, in the current scenario, an error (401-status) occurs. This prevents the execution from going into the else statement. Can someone provide assistance on how to properly handle or catch this error? Thank you.

Answer №2

Using the method entails providing 3 specific parameters: the first one is executed upon receiving a successful response, the second is triggered in case of an error response, and the third is activated once the process is completed. Give this a try:

this.fetchData(params).using(response => {
     console.log('Success');
}, error => {
     console.log('Error')
});

I highly suggest checking out the angular tutorial as well as the Rxjs Subscribe documentation.

Answer №3

Another option is to utilize the .catch method:

this.http.post(this.serverUrl+'login', loginForm.value, {headers: headers})
        .subscribe(response => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        }).catch((err)=>{console.log(err)}); 

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

Function type cannot be restricted by type guards

I have a function that takes in parameters with similar structure and uses type guards internally to determine the type of parameter being passed. type Example1 = { data: 'data', param1: 'yes' } type Example2 = { data: 'data ...

display the picture depending on the circumstances

Is there a way for the image tag to display different images based on a condition? I attempted the code below, but it's not displaying the image: <img src="{{row.image}}!=null?'data:image/jpeg;base64,{{row.image}}':'./assets/img/qu ...

Utilize ngx-bootstrap/typeahead within an Angular Directive for enhanced functionality

Currently, I am implementing an autocomplete feature on my webpage using ngx-bootstrap/typeahead. Below is the code snippet that I have been utilizing: <input type="text" class="form-control" name="countryName" autocomplete="off" [(ngModel)]="asyncSele ...

A guide to resolving the error "Cannot read properties of undefined (reading 'length')" while implementing pagination with react, Material-UI, and TypeScript

As I work on my code, my goal is to display a limited number of cards per page based on the data stored in a JSON file. I anticipated that clicking on the ">" or "<" icon would navigate to the next or previous page respectively, updating the displaye ...

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

Angular 6 and Bootstrap 4 unite in a powerful collaboration, showcasing a stunning carousel feature enhanced with dynamic

Currently I am working on creating a carousel using Bootstrap 4 and Angular 6. Everything is functioning properly, except for one issue that I am facing. I am trying to add Indicators dynamically by using a *ngFor loop. The problem I am encountering is tha ...

Utilizing Typescript and Jest to prevent type errors in mocked functions

When looking to simulate external modules with Jest, the jest.mock() method can be utilized to automatically mock functions within a module. After this, we have the ability to modify and analyze the mocked functions on our simulated module as needed. As ...

What is the best way to instantiate an object of type <T>?

I'm encountering an issue: class Collection<T extends IModel> extends Event implements ICollection<T> { constructor(array: any[] = []) { super() this._init(array) } private _init(array: any[]) { array.forEach( ...

Using the Post method in Angular will result in a 400 status code being returned

I am a student developer working with the Angular platform. I have my own API and a post method that looks like this: [HttpPost] [Route("login")] public async Task<ActionResult<User>> LoginUser([FromBody] User _user) { var joinedUser = _co ...

Issue with Observable subscription not receiving notifications

I am currently working with an Observable to convert a promise into a subscription. This leads to a collection that requires iteration in order to call an HTTP Service on each element. I am using forkJoin to wait for all the calls to finish before procee ...

TypeScript throwing error: Attempting to call a potentially 'undefined' object goes against coding principles

In the snippet below, an error is encountered: example/not-following.ts:15:1 - error TS2722: Cannot invoke an object which is possibly 'undefined'. 15 run(true).maybe(); ~~~~~~~~~~~~~~~ Snippet: interface Example { maybe?: () => voi ...

Difficulty with rendering content from Angular routes

Currently, I am working on a movie application where users can click on a details button to view information about a specific movie. However, I am facing an issue in displaying the information for the selected movie without showing all the movies at once. ...

The ts-loader, antd, and typescript trio hits a stumbling block with the module index.less nowhere to

I am incorporating the antd React component library in my project and I'm using ts-loader to efficiently load the components. Currently, I am facing an issue while trying to configure webpack to transpile less files. The error I am encountering is as ...

Developing test cases for mat-autocomplete feature that customizes customer search

I am currently in the process of writing unit tests for an Angular app, specifically Angular6. One specific component that I am focusing on contains mat-autocomplete functionality. My goal is to ensure that the users are properly filtered based on the inpu ...

Exploring Angular2: Understanding how to retrieve an object with an unknown key

I am trying to showcase a specific value from different objects within a template. The path of the desired value depends on the object being referenced. For example: let obj = { "a": "a", "b": { "1": "1", "2": "READ ME" } } let ...

Converting TypeScript interface types into an array of classes: Serialization process

I am encountering an issue with typescript typings in my current project. Specifically, I'm developing a small game engine that follows the entity-component-system model. My goal is to convert types of interfaces into an array of classes to define the ...

Refilling state through an NgRx Effect

I am facing a situation where I have JSON data stored in my effect, which was initially generated using JSON.stringify(state), and now I need to insert that JSON string back into the state in order to update the application. As someone new to Angular and N ...

Utilizing Interface Merging: Determining the Appropriate Instance Type for Field Types

I am in need of writing a definition file for an external library. I have augmented a class using interface merging and there are situations where a field of the library class is of the same type as the instance itself. Here is a snippet of demo code: // ...

Switch the paper tab to a dropdown menu in Polymer.js

Can someone assist me in transforming the paper tab into a paper drop down menu in polymer JS? I want the drop-down to appear with a list of values when hovering over the Top menu. Activity Execution <paper-tab cla ...

Display default value of 0.00 in Angular 4 input fields with type "number" - how can it be done?

I need the users to view "0.00" in the number-type text box. Here is the HTML I am currently utilizing: **<input type="number" class="form-control" min="0.00">[(ngModel)]="_vendorDetailsDTO.openingBalance" step="0.01" name="bal" #bal="ngModel">* ...