Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of

core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined

I realized that the Exception stemmed from a Template trying to access a specific property:

{{project.collaborators["0"]["fullName"]}}

While searching for solutions, I came across a helpful answer.

However, I am interested in creating a global service that can automatically replace missing or empty properties with a default value, such as -

This would streamline the code and reduce the chances of bugs.

// undefined-obj.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class UndefinedObjectsGlobalService {
private charecterToReplace: string = '-'; // set default value

replaceDefaultCharacter(object: any, characterToReplace: string): any {
        this.characterToReplace = characterToReplace;
        // create instance vars to store keys and final output
        let keyArr: any[] = Object.keys(object),
        var dataArr: any[];

        // loop through the object,
        // pushing values to the return array
        keyArr.forEach((key: any) => {

                // if key is null at any iteration then replace it with the given character
                if (key == null){
                        dataArr.push(object[key] = this.characterToReplace); 
                        // else push 
                } else{
                        dataArr.push(object[key]); 
                }

        });

        // return the resulting array
        // need to convert it back to object any idea ?
        return dataArr;
        }
}

Since I am new to Angular, the class UndefinedObjectsGlobalService may contain bugs. I would appreciate any help.

Answer №1

It appears that you are attempting to access a property of an object that does not exist.

Angular has a built-in elvis operator to assist with this type of situation.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Greetings {{name}}</h2>
      {{collaborators["0"]?.fullname}}
    </div>
  ',
})
export class App {
  name:string;
  collaborators: [{fullname: string}];
  constructor() {
    this.name = 'Angular2'
    this.collaborators = [];
  }
}

You can view a demonstration here.

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

Navigating to a different page using the browser address bar causes the context to be reset

Upon receiving the user's data from the API on the login page, it is set in the user context. Subsequently, upon redirection to the AdminPanelApp, the data within the user context is displayed accurately. However, if I am in the AdminPanelApp and navi ...

Angular 7 swiper experiencing navigation issues

I have been attempting to implement the swiper slider but I am facing issues with navigating through slide content. You can find my code on stackblitz - swiper in the last horizontal tab. Here is the TypeScript code: ngOnInit() { var swiper = new Sw ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

Can CSS be used to communicate to JavaScript which media queries are currently in effect?

Is there a way for Javascript to detect when a specific CSS media query is active without repeating the conditions of the media query in Javascript? Perhaps something similar to an HTML data attribute, but for CSS. For example: CSS @media (min-width: 94 ...

A comprehensive guide on constructing a literal object in Typescript by combining an array with an object

Recently, I came across this Typescript code snippet: type SortedList = T[] & {_brand: "sorted" }; function binarySearch<T>(xs: SortedList<T>, x: T): boolean let low = 0; let high = xs.length - 1; while (high ...

Could you please explain the specific distinctions between pipe and map within Angular 7?

After extensive research, I'm still struggling to understand the distinction between pipe and map in Angular 7. Should we always include a pipe in Service.ts file in Angular 7? Appreciate any clarification on this matter. ...

The total number of items in the cart is experiencing an issue with updating

For a recording of the issue, click here: While everything works fine locally, once deployed to production (vercel), it stops working. I've tried numerous approaches such as creating a separate state in the cart, using useEffect with totalQuantity in ...

Can anyone recommend a reliable JavaScript library for creating resizable elements?

I am looking to incorporate resizable functionality for a textarea. While I have experimented with jQuery UI's "resizable" feature, it doesn't quite meet my needs. I appreciate jQuery, but the resizable option falls short in allowing me to resize ...

Tips for converting an Array object to JSON format

After much effort, I have finally managed to format my data as valid JSON with the following Javascript code: var roles = getSelectedRoles(); // returns an Array object /* TODO: Explore better methods for incorporating roles into JSON data */ var rolesSt ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

"Encountering a problem during the installation of the Angular

After investing numerous hours, I am still unable to identify the issue with running an angular based project. node version: v12.16.1 I executed npm install -g @angular/[email protected] However, upon entering the command ng build --prod, I enco ...

A guide to incorporating dhtmlx scheduler into your Angular 4 project

Currently, I am utilizing dhtmlx scheduler to handle my events. While I was able to import the necessary js files successfully, I have encountered an issue when it comes to saving data in the database. My backend is built using Spring Boot framework. Can ...

What is the best way to incorporate intervals and polling in Angular 2 for seamless integration with Protractor?

I have an angular2 application that I am looking to test using protractor. Within this application, there is a page featuring a graph that updates at regular intervals with data generated on its own. It appears that one aspect of protractor is the abilit ...

JQuery is having issues with $(this) and the find function not working properly

I am attempting to access a child of the div with the class form-group, specifically, I want to display the value of the input element. <div class="form-group"> <label>text</label> <input name="text" type="text" class="form-co ...

The successful conversion of Typescript to a number is no longer effective

Just the other day, I was successfully converting strings to numbers with no issues. However, today things have taken a turn for the worse. Even after committing my changes thinking all was well, I now find that when attempting to cast in different ways, I ...

Utilizing a Grunt task to inject code into an AngularJS file

Hey there! I'm currently looking for a way to add some code into my app.js file that will only execute when I run the "grunt serve" task. This code is just two lines of javascript that should be present when I test the app on my local environment. Unf ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Utilize the identical function value within a Vue template

In my template, I am encountering a recurring situation where I need to retrieve a value from a function. This function takes parameters from the template (such as the index of a v-for loop) and returns a result that is then displayed on the template. The ...

Could one potentially assign number literals to the keys of a tuple as a union?

Imagine having a tuple in TypeScript like this: type MyTuple = [string, number]; Now, the goal is to find the union of all numeric keys for this tuple, such as 0 | 1. This can be achieved using the following code snippet: type MyKeys = Exclude<keyof ...