AngularJS 2 - error when trying to bind inner properties: ERROR: Unable to access property value due to undefined variable

I have been troubleshooting a problem with my AngularJS 2 app using Typescript. The issue arises when I attempt to access a property from the Typescript class in the HTML page using data binding. I have provided the relevant files below for reference. If there is something I am overlooking, please do let me know. I have been stuck on this particular issue for over two days now and feel like I have exhausted all possible solutions.

Below are the Typescript classes:

export class ApproveBooking {
constructor(
    public name: string,
    public form: DynamoForm,
    public cabBooking: CabBooking) {}
 }

export class DynamoForm {
constructor(
    public formFields: DynamoFormField[]) { }
 }

export class DynamoFormField {
constructor(
    public fieldName: string,
    public fieldId: string,
    public fieldLabel: string,
    public fieldType: string,
    public fieldValue: string,
    public required: boolean) { }
}

export class CabBooking {
constructor(
    public id: number,
    public bookingId: string,
    public status: string,
    public notes: string,
    public user: boolean,
    public travelDateString: string,
    public travelTimeString: string,
    public pickupLocation: string,
    public dropLocation: string,
    public approver: string,
    public approverAction: string,
    public approverComments: string,
    public approvedDate: string,
    public cabDriver: string,
    public cabDriverAssignedDate: string,
    public createdDate: string,
    public modifiedDate: string) { }
}

Here is the service that retrieves JSON data from the server and assigns it to the 'ApproveBooking' class:

... [service content here] ...

JSON data received from the server looks like this:

... [JSON data sample here] ...

Utilizing the AngularJS component which utilizes the service method to populate one of its properties:

... [component content here] ...

The template for the component's HTML view:

... [HTML template content here] ...

The issue occurs when trying to access the inner property of approveBooking in the HTML view, resulting in an error. Here is the specific error message:

TypeError: Cannot read property 'bookingId' of undefined in [{{approveBooking.cabBooking.bookingId}} in ApproveCabBookingComponent@8:10]

For your information, everything works as expected when using flat JSON data and a flat Typescript class.

Answer №1

My investigation revealed that the issue stemmed from the component template (HTML) being rendered before the JSON data was available to the component.

A useful post on this topic can be found at: Angular2: How to load data before rendering the component?

Finding a solution in the provided post, I made updates to the AngularJS component as shown below.

@Component({
templateUrl: 'app/approver/approver_approvebooking.html'
})

export class ApproveCabBookingComponent implements OnInit {
private errorMessage: string;
private approveBooking: ApproveBooking;
private isDataAvailable: boolean;

constructor(
    private _logger: Logger,
    private _router: Router,
    private _routeParams: RouteParams,
    private _cabBookingService: CabBookingService) { 

    this.isDataAvailable = false;
}

ngOnInit() {
    let bookingId = this._routeParams.get('bookingId');
    this._logger.log("bookingId inside ngInit = " + bookingId);

    this.approveBooking = this._cabBookingService.getSingleCabBookingForApproval(bookingId)
        .subscribe(
            approveBooking => {
                this.approveBooking = approveBooking;
                this.isDataAvailable = true;
                this._logger.log("this.approveBooking => " + JSON.stringify(this.approveBooking));
            },
            err => {
                this._logger.log("Error while accessing approveBooking...error, JSONed = " + err.status + "," + JSON.stringify(err));
            },
            () => console.log('Approve Cab Booking Entity Fetched!');
            );
}
}

The view corresponding to the component was also adjusted to utilize the 'isDataAvailable' property.

<div *ngIf="isDataAvailable">
    <div class="col-md-12 title-panel">
        <h3>Manage Booking </h3>
    </div>
    <div class="col-md-12 content-panel">
        <form (ngSubmit)="onSubmit()">
            <div class="row">
                <div class="col-md-12">
                    <h4 class="label-heads">Booking ID</h4>
                    <div class="form-value">
                        <span>{{approveBooking.cabBooking.bookingId}}</span>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

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

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

The react transition group fails to add the necessary CSS classes to the specified div

Regardless of whether I utilize React transition group, Tailwind, pure CSS, or any other framework, no transitions seem to occur when I structure my simple component in the following manner. I have experimented with various frameworks, but the outcome rema ...

Tips for transferring the output of a JavaScript async function to a Python variable

var = driver.execute_script("setTimeout(function(){ return [1,2,3]; }, 1000);") Utilizing the Selenium method execute_script, I am attempting to extract data from a website using javascript and assign it to a python variable var. The challenge a ...

What could be causing my Javascript prompts to not appear in my Express.IO .ejs file?

I am fairly new to JavaScript and exploring Node with Express.IO. I'm currently working on a project that involves tracking real-time connections made by different 'users' to the server. However, I've encountered an issue where my promp ...

Transmitting data from the front end to the server in React/Shopify for updating API information using a PUT request

After successfully retrieving my API data, I am now tasked with updating it. Within my component, I have the ability to log the data using the following code snippet. In my application, there is an input field where I can enter a new name for my product an ...

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

AngularJs Controller with explicit inline annotation

I usually inject dependencies using inline annotations like this angular.module('app') .controller('SampleController',['$scope','ngDependacy',sampleController]); function sampleController($scope,ngDependacy) { ...

Resolving label overlapping issue in Chart.js version 2

I am currently utilizing Chart.js 2 for a project of mine. I've successfully customized the style, but there's one persistent issue that I can't seem to resolve and it's becoming quite frustrating. Occasionally, the last label on the x ...

How can I define the PropType for an object containing a combination of strings and functions?

Trying to define a prop, which is an object of strings and functions. I set proptypes as component.propTypes = { propName: PropTypes.objectOf(PropTypes.oneOf([PropTypes.string, PropTypes.func]) } However, I encountered an error message stating that it r ...

Utilizing Laravel 5.3 and Vue.js for Dynamic AJAX Calls Based on Select Box Selections

I am looking to display a newly added record in a select box once it has been inserted into the table. Below is my Laravel HTML code: <div class="form gorup"> <select class="form-control" > <option @click="called" ...

Tips on extracting specific information from nested JSON objects

I have a packet with the following data and I need to extract a specific part: "data":"YOeNkAAg1wQAYjm/pg== Is there a way to achieve this using JavaScript in node-red? { "payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent { ...

Leveraging a single Axios request across various components

My current setup involves making a simple Axios call in this way: .get('https://myAPI.com/') .then(response => { this.info = response.data }) Subsequently, I utilize a v-for array loop on my components to display the retrieved data. ...

Implementing translation functionality within an AngularJs controller

Utilizing angular translate for translating certain words in the controller, with translation stored in json files within the html. // LABELS var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septe ...

Creating an extra dialogue box when a button is clicked in React

Having an issue with displaying a loading screen pop-up. I have an imported component named LoadingDialog that should render when the state property "loading" is true. When a user clicks a button on the current component, it triggers an API call that chang ...

"Interacting with the ng-keypress event causes the page to smoothly scroll

As a newcomer to angularjs, I am trying to figure out why my component (which simulates a "checkbox" using fontawesome icons) causes the page to scroll down when the user presses the space key. Here is a snippet of my component : ugoFmk.component(' ...

Facing a node.js installation issue on Windows 10 while using Visual Studio Code (VS

Issue encountered while trying to execute "DownloadString" with one argument: Unable to establish a secure connection due to SSL/TLS channel creation failure. At line:1 char:1 + iex ((New-Object System.Net.WebClient).DownloadString('https ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

Generating observables from form submission event

Note: I am completely new to Angular and RXJS. Currently, I am working on a simple form where I want to create an observable. The goal is to listen for submit events and update a value within the component. However, I keep encountering an error message sa ...

Sending the "accurate" data from the specific cell in a UITableViewController to a ViewController

I'm encountering the same issue here. I am struggling to pass the precise data from one TableViewController to another ViewController. Even though I have all the necessary data from JSON, when I select a row, it displays the data from the last row ins ...

The functionality of window.localStorage.removeItem seems to be malfunctioning when used within an $http

Currently, I am sending a post request to my web service and upon successful completion, I am attempting to remove a token from local storage. Here is the code snippet: $http.post("MyService/MyAction").success(function (res) { if ( ...