An error was encountered when attempting to convert a value that is either undefined or null to an object in Angular 9

Upon invoking a service call that interacts with an API to retrieve JSON data, I encountered an issue during the build pipeline of my application. The error message "Uncaught (in promise) TypeError: Cannot convert undefined or null to object." halted the build process, despite the service call working perfectly fine locally and passing all tests. My technology stack includes angular 9 and typescript.

This is what my subscribe function looks like:


houseData: HouseValueObject;
houseNumber = '12345';

callHouseService() {
   this.streetHouseService.getHouseData(this.houseNumber).subscribe(
     async (data) => {
       this.houseData = await data;
       const keys = Object.keys(this.houseData.extensiveHouseData);
       this.extensiveHouseDataList = keys.map(k => this.houseData.extensiveHouseData[k]);
}
)
}

The structure of the getHouseData method can be summarized as follows:

export class HouseService {
  private readonly relativeURL = 'services/api/houseinfo/'
  
  constructor(private http: HttpClient) {
  
  getHouseData(houseNumber: string): Observable<HouseValueObject> {
   return.this.http.get<HouseValueObject>(this.relativeURL + houseNumber + '/');
}
}
}

Defined within the HouseValueObject class are properties such as numberBathrooms and extensiveHouseData.

export class HouseValueObject {
   numberBathrooms: number;
   extensiveHouseData: HouseValue[];
}

I utilized async and await in an attempt to delay execution until the promise was resolved, ensuring the availability of JSON data for the const keys = Object.keys... portion of the code. However, it seems that this approach did not yield the desired results. Can anyone provide insight on how to effectively defer execution until the promise resolves, thereby enabling the successful operation of const keys = Object.keys... as intended?

Answer №1

In my opinion, rewriting the service to return a promise would greatly improve readability.

HouseService:

fetchHouseData(houseNumber: string): Promise<HouseValueObject> {
   return this.http
      .get<HouseValueObject>(`${this.relativeURL}${houseNumber}/`)
      .toPromise<HouseValueObject>();
}

Component:

async requestHouseData(): Promise<void> {
  this.houseData = await this.streetHouseService.fetchHouseData(this.houseNumber);
  this.extensiveHouseDataList = Object
    .keys(this.houseData.extensiveHouseData)
    .map(k => this.houseData.extensiveHouseData[k]);
}

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

Typescript: Creating a new type by filtering an interface for matching properties

Imagine you have an interface structured like this: interface endpoints { "/api/user/{id}": { get: operations["getUserGET"]; }; "/api/user/add": { put: operations["addUsingPUT"]; }; ... } Is it pos ...

Guide to loading TypeScript modules with RequireJS in an ASP.NET MVC/Visual Studio setup

If we consider a scenario where there are 2 files named test1.ts and test2.ts. The content of test1 is as follows: export const x = 1 And the content of test2 is: import { x } from './test2' alert(x); Upon running the application, an error m ...

Angular's reactive form feature does not have built-in support for ngIf

I am facing an issue with a form group where I need to display one of the required inputs using ngIf. However, even if this input does not exist, the form control still checks it and returns that the form is not valid. Here is my code: HTML: <form [form ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...

Implementing a Typescript directive in AngularJS to create a class

After using AngularJS for quite some time, I decided to explore Typescript. I managed to convert most of my Angular code to Typescript and found it beneficial, especially when working with services. However, I am struggling to convert the following direc ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...

How to retrieve all the days of each month starting from a particular day with the help of momentJS in Angular

I am currently working on developing a custom day picker that will show all the days of the month in a calendar format, displaying them from Sunday to Saturday. Currently, I am only able to display dates from the 1st of the month onwards. https://i.sstati ...

What is the significance of including parameter names in Typescript function type signatures?

Just diving into typescript for the first time, so bear with me... I decided to create a simple filter function for a container I had created class Container<T> { filter(predicate: (T) => boolean): Container<T> { for(const elem ...

Is there a source where I can locate type definitions for Promise objects?

In the process of creating a straightforward class called Primrose, I am extending the global Promise object in order to include additional methods like resolve and reject. export class Primrose<Resolution> extends Promise<Resolution>{ priv ...

Enhance Your NestJS Experience: Using Interceptors for Mapping and Error Handling

I'm looking for a NestJS interceptor that can log requests in all scenarios, including both successful executions and errors. Below is an example implementation: public intercept(context: ExecutionContext, next: CallHandler): Observable<any> { ...

Is it acceptable to operate a live website with a hybrid implementation of Angular and AngularJS?

I have an existing AngularJS app that I am eager to update to the newest version of Angular. However, a major hurdle is that the app relies on numerous third-party libraries that are not compatible with Angular v.2. Is it feasible to operate a combined An ...

Troubleshooting: Issues with Angular2 compatibility on Safari version 9.1.2

I am encountering an issue with running my angular2 app on Safari 9.1.2. It works fine on all higher versions of Safari as well as other browsers such as Chrome, Firefox, Opera, and Edge. However, when I try to run it on Safari 9.1.2, I receive the followi ...

An issue has occurred: The function _co.collapsed is not of type function

Within my HTML template, I am utilizing the ngFor directive as shown below: <div class="card" *ngFor="let item of mydataarray"> <div class="card-header" (click)="item.isCollapsed = !item.isCollapsed"> <div class="card-body" [collapse]="ite ...

ngc encountering issues when compiling project with untyped third-party libraries

Utilizing a third-party library without defined types, the project is being developed using Angular CLI (version 1.0.0-beta.29) and the library is declared in typings.d.ts. In this instance: declare module ‘xml2js-es6-promise’; The project compiles an ...

Cypress - AG-Grid table: Typing command causing focus loss in Cell

Encountering a peculiar issue: I am attempting to input a value into the cell using 'type()'. My suspicion is that each letter typed causes the focus on the cell to be lost. It seems that due to this constant loss of focus and the 'type()& ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Experiencing difficulty when trying to link control with form in Angular Reactive forms

I am currently working on Angular Reactive forms and facing an issue with binding form controls dynamically. Initially, I have a form array in form group, and then I push form groups into the form array to add form controls dynamically. However, I encounte ...

Is there a way to alter the value of an Observable using Knockout and Typescript within its subscription?

Question: What is the best way to update the value of an Observable from within its subscription using Knockout and Typescript? I am currently in the process of refactoring some old Knockout code to use Typescript. While going through the code, I came acr ...