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

What is the best method to update the content of one div with content from another page using AJAX?

Having trouble achieving smoother page loads? My goal is to utilize AJAX to specifically fetch a certain div from another page and then swap out the content of a div on this current page with the response. Below is my JavaScript script that uses AJAX to r ...

Having difficulty updating the border color of Material UI Input when it is in focused or unfocused state

I can't seem to figure out why this code isn't working as expected. I'm trying to target the MuiInputBase-root element, specify that it should have a blue border by default, and then change the border color to red when focused. Can someone h ...

Interactive data table feature in React, transferring selected row data to a modal pop-up

I am currently developing an offline Progressive Web App (PWA) using ReactJS and have integrated the react-data-table-component, which has been very helpful so far. Within the table, I have implemented an onRowClicked function that triggers whenever a row ...

Show more/less of the text snippet and main body of information

I am currently in the process of setting up a basic WordPress blog with only one page dedicated to the blog archive. However, I have encountered an issue. I want to implement a toggle functionality that allows visitors to easily navigate through posts on t ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Utilize jQuery to extract various input/select box values and compile them into an array for submission using .ajax()

I am currently facing an issue with dynamically generated forms using PHP and updated with jQuery's .appendTo() function as visitors interact with it. My main goal is to collect all input text and select box values from the current form and submit the ...

Is there a way to implement this code to filter every column in the grid?

I have been using this code in my grid view, but it only filters one column of the grid. Now I want to modify the code to filter multiple columns. I tried implementing a loop, but it seems like the code is not working correctly. Is there a way to adjust t ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

Integration of AngularJS with PHP for Seamless User Authentication

As a newcomer to angularjs, I find the Login Process a bit confusing. Every time I log in, I'm automatically redirected to a specific page that is already set in the code. I just want a simple check to see if the user is logged in. If they are, then ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

The Express Validator is unable to send headers to the client once they have already been processed

I recently integrated express-validator in my Express JS project, but encountered a warning when sending invalid fields to my api: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This ...

PHP: Link to logo in different folder by including 'nav.php'

I am facing an issue with my nav.php file: <div> <!-- there's a lot of code here so I want to write it once and include it in all pages within the main folder as well as subfolders <img src="logo.png"> </div> The structur ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...

Guide to iterating through different endpoints in a predetermined sequence

I am facing a challenge with testing various endpoints using different login credentials. When looping through the endpoints, the results are not appearing in the sequential order due to asynchronous nature. My goal is to iterate through each endpoint wit ...

Making sure the axios API call is completed before rendering the child component with props

Check out the snippet of code I've provided: function StoryCarousel(props) { const [ivrDests, setIVRDests] = useState([]); useEffect(() => { async function getIVRDests() { var data = { "customer-id": ...

"Exploring the depths of nested JSON objects with Retrofit in Android development

I'm having trouble parsing dynamic JSON data in Retrofit. Here is a sample of the JSON structure with keys that are generated dynamically. What kind of POJO definition should I use for this type of JSON data? { "Fri Mar 23 2018 17:35:36 GMT+0 ...

Errors related to CodeIgniter sessions can cause unexpected behavior in

I am new to the CodeIgniter framework and I am facing an issue with setting a session on my website. When I hit the back button in my browser, it takes me back to the main login page of my website, and when I click next, it shows a not found page. Even on ...

Guide on converting JSON encoded data into a JavaScript array

I have a few web pages that display results in the following format: [{"id":"1","company":"Gaurishankar","bus_no":"JHA 12 KH 1230"}, {"id":"2","company":"Gaurishankar","bus_no":"BA 2 KH 2270"}] Now, I want to take this JSON encoded data and use it in a J ...

Loopback: Unable to access the 'find' property as it is undefined

I've come across a few similar questions, but none of the solutions seem to work for me. So, I decided to reach out for help. I'm facing an issue while trying to retrieve data from my database in order to select specific parts of it within my app ...

Creating a dynamic model in an AngularJS directive using a JSON object

I am struggling with utilizing a json file that contains objects storing properties for a directive. Despite my attempts, I cannot seem to access the json obj model value within the directive. Does anyone have any insights into what I might be doing incor ...