Handle empty response from endpoint response

I'm facing an issue with a method that subscribes to an endpoint for a response. In some cases, the endpoint returns null and I need to handle this scenario.

public list: Array<any>;

this.GetList(this.getListRequest)
  .subscribe(
    (resp) => {
      this.progressSpinnerService.stopLoading();
      this.list = resp.loanAdjustmentResult.loanAdjustmentList; //error is here
    },
    (error) => {
      this.progressSpinnerService.stopLoading();
      this.handleServiceError(error); // error handling.
      this.serviceError = true;
    }
  );

The response from the service has the following structure:

{
   "header":{
      "statuscode":"0",
      "userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
      "wfpt":null,
      "paginationContext":null,
      "reasonCode":null
   },
   "accountNumber":null,
   "loanAdjustmentResult":null
}

I'm encountering an ERROR

TypeError: Cannot read property 'loanAdjustmentList' of null
at the line mentioned above. Any suggestions on how to handle this error?

Answer №1

Potentially

  1. Include a condition to verify if the property is null before accessing it (this will maintain the original value of this.list):

    if (resp.loanAdjustmentResult != null) {
      this.list = resp.loanAdjustmentResult.loanAdjustmentList;
    }
    
  2. Utilize the optional chaining operator (this will result in this.list being undefined):

    this.list = resp.loanAdjustmentResult?.loanAdjustmentList;
    

Answer №2

To implement the safe navigation operator, you can use ?. as shown in the example below:

this.collection = response.data?.itemList;

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

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

How can I center a Bootstrap modal vertically and make it responsive?

Is there a way to vertically center the bootstrap modal? I have been searching for a solution, but none seem to be responsive or effective. My website is using Bootstrap 3. The modal does not adjust properly on smaller screens or when the browser window i ...

Creating a custom HTTP request in Angular 2

Utilizing a custom HTTP request class to add an Authorization Header to all requests has been successful on the majority of android devices. However, some customers have reported receiving a 'No internet connection' error despite having a functio ...

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

Transferring information between two tables in a MongoDb database

My current database in mongo is named "sell" and it contains two tables: "Car" and "Order". In the "Car" table, there is an attribute called "price". When I run the following command in the mongo shell: db.Order.aggregate([ { $lookup: { from: ...

I am able to view the node-express server response, but unfortunately I am unable to effectively utilize it within my Angular2 promise

https://i.stack.imgur.com/d3Kqu.jpghttps://i.stack.imgur.com/XMtPr.jpgAfter receiving the object from the server response, I can view it in the network tab of Google Chrome Dev Tools. module.exports = (req, res) => { var obj = { name: "Thabo", ...

The JavaScript function is not being activated by clicking on Selenium in Chrome

Take a look at the HTML snippet below: <table class="table-main "> <thead> <tbody> <!----> <tr class="" ng-if="mapCtrl.isAdded" style=""> <td/> <td> <td> <t ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

Is it possible to trigger the alert message by utilizing this code snippet?

Is it possible to display a message using this function? var start_database = function() { alert('hello'); }; window.setTimeout(start_database, 1000); ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

Could you provide an explanation of the styled() function in TypeScript?

const Flex = styled(Stack, { shouldForwardProp: (prop) => calcShouldForwardProp(prop), })<LayoutProps>(({ center, autoWidth, autoFlex, theme }) => ({ })); This syntax is a bit confusing to me. I understand the functionality of the code, b ...

Error encountered in MVC 5: When using jQuery to assign a value to an object, the

Currently tackling a web development project as a newbie in the field and running into an issue with this snippet of code (which sets the end date to tomorrow if left blank): var date = new Date($('#txtStartDate').val()); var tomorrow = date.ge ...

Ways to initiate a language shift in the **JavaScript yearly calendar** when the language is modified in an Angular application

1. I have incorporated ngx-translate into my Angular application for translation purposes. 2. I have successfully implemented the ability to switch languages during initialization by specifying options like {language:'ja'} for Japanese within th ...

How can one determine the source of change detection activation in Angular 2?

I just launched a new component and it appears to be causing change detection to occur multiple times per second: // debugging code ngDoCheck() { console.log('DO_CHECK', new Date().toLocaleTimeString()); } Results: https://i.sstatic. ...

Emptying the trumbowyg editor within an Angular environment

I am currently experiencing issues with the trumbowyg editor in a project I'm working on. I am able to update the editor by changing its model but cannot seem to clear its content using $scope.editorModel = '';. For a more detailed explanati ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...