Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests.

I want to implement error handling by using the HandleError mechanism described on Angular's Communication Page to properly display any errors encountered. However, I am facing an issue with the error handler in my data service layer throwing the error message:

Argument of type 'Observable<never>' is not assignable to parameter of type '(err: any, caught: Observable<Record>) => ObservableInput<any>'

Upon inspecting the JSON object and API URL, everything seems to be correct. I can successfully reach the controller by manually testing the JSON object and URL using Postman.

If anyone has insights or suggestions for effective error handling and logging, it would be greatly appreciated.

Below is the component logic:

updateRecord(record_id: number, newRecord: any): void
{
   this.recordService.put<Record>(record_id, newRecord);
}

Data service logic:

put<Record>(record_id: number, record: Record): Observable<Record> {
    var url = this.baseUrl + `api/record/${record_id}`;
    let output = this.http.put<Record>(url, record, {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    })
    .pipe(
        catchError(this.handleError('put<Record>', record))
    );

    return output;
 }

Error Handling Function:

private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
        consol e.error('An error occurred:', error.error.message);
    } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong.
        console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // Return an observable with a user-facing error message.
    return throwError(
        'Something bad happened; please try again later.');
}

Controller logic:

[HttpPut("{id}")]
public async Task<ActionResult<Domain.Record>> Put(int id, [FromBody] Domain.Record record)
{
    //Confirm the request record and ID record being update match
    if (id != record.record_id)
        return BadRequest();

    //Modify the state
    _context.Entry(record).State = EntityState.Modified;
    //Update the records in DB.records, throw appropriate error if there is one.
    try
    {
        await _context.SaveChangesAsync();
    }
    catch(DbUpdateConcurrencyException)
    {
        if (!RecordExists(record.record_id))
            return NotFound();
        else
            throw;
    }

    //return 200 OK
    return NoContent();
}

Answer №1

It seems like a subscription was missing, as mentioned in the comments of the main question.

In RXJS, an Observable needs to be subscribed to in order for it to execute. So, instead of just:

updateRecord(record_id: number, newRecord: any): void
{
   this.recordService.put<Record>(record_id, newRecord);
}

You should use:

updateRecord(record_id: number, newRecord: any): void
{
   this.recordService.put<Record>(record_id, newRecord).subscribe((result) => {
    // process the results here
   };
}

If you don't subscribe, you won't receive any results from the HTTP call made by recordService.put().

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

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

Instructions for including a class are ineffective

I am trying to dynamically add a class to a div based on two conditions. To achieve this, I have created a custom directive as shown below: import { Directive, HostBinding, Input } from '@angular/core'; @Directive({ selector: '[confirmdia ...

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

Generate PDF document from grid

While working with the obout grid, I encountered an issue when attempting to export the grid data to PDF. The export process worked seamlessly when populating the grid using sqldatasource. However, when filling the grid using a stored procedure and functio ...

Angular routing is showing an undefined ID from the snapshot

When a user attempts to update a student, I pass in the student ID. The update successfully redirects to the updateStudent page and displays the student ID in the browser link. However, within my app component, it shows as undefined. Student View componen ...

Is it possible for me to create an interface that is derived from a specific type?

Is there a way to define an interface in TypeScript where the keys are based on a specific type? For example: type FruitTypes = "banana" | "apple" | "orange"; interface FruitInterface { [key: string]: any; // should use FruitTypes as keys instead of str ...

Using Karma-Jasmine to Import Spy without anyImplicitAny

If I include the configuration setting noImplicitAny in the tsconfig.json file of my Angular 4+ project: "noImplicitAny": true, ...and then try to import and use Spy in a unit test: import { Spy } from "karma-jasmine"; I encounter this console error wh ...

What is Prettier's reasoning for suggesting the use of `;` before a destructuring assignment declaration?

I am facing an issue with the if block within my Angular component: if (desc.length > 0) { [this.errorMsg] = desc } The problem arises as Prettier suggests adding a ; at the start of the destructuring assignment: if (desc.length > 0) { ;[thi ...

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

Efficiently utilizing ngrx by orchestrating various services and actions to achieve accurate mapping

Combining multiple effects into one is my current goal due to an issue with dispatching actions separately. The aim is to execute sequentially after verifying the value returned from the first service call. Here are the three separate effects I have: @Eff ...

Setting up the CHROME_BIN path in Jenkins environment variable for running Headless Chrome without Puppeteer can be achieved by following these

Currently, I am facing an issue in my Angular project where I can successfully run tests using Karma and Jasmin on my Windows local machine with headless chrome. However, Jenkins is giving me an error stating "No binary for ChromeHeadless browser on your p ...

The combination of Sequelize and TypeScript does not support the usage of the .create method with type attributes

The IDBAttribute - interface IDBAtribute { readonly id: number; readonly createdAt: Date; readonly updatedAt: Date; } User attributes defined as IDBMoviesAttributes - interface IDBMoviesAttributes extends IDBAttribute { readonly title: str ...

Generating lasting and distinctive hyperlinks

Currently, I am in the process of developing an application that enables users to search for and compile a collection of their preferred music albums. At this stage, users have the capability to create their personalized list. However, my next objective i ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

The mat-checkbox is failing to accurately reflect its checked state

This code snippet is from my .html file: <mat-checkbox [checked]="getState()" (change)="toggleState()">Example Checkbox</mat-checkbox> <br><br> <button mat-raised-button color="primary" (click)=" ...

I am looking to include both a space and a comma in the State dropdown value in an Angular application

I am facing an issue with my dropdown in Angular 9. When the State is more than one, it displays without any space between them. I want it to show like: Licensed State:ARCA I need like: AR, CA This is the code I have so far: <ng-c ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...