Troubleshooting tip for Angular 2: Issue with accessing object properties using dot notation

When it comes to Angular, there are two methods for accessing object values:

1. Access the property of the object using dot notation (obj.property).

2. Access the property of the object by passing in a key value pair, for example obj["property"].

If I display {{ page | json }}, I can see an object containing all the list items.

https://i.sstatic.net/UWKi4.png

If I try 'page.id' or any other property, I encounter an error:

EXCEPTION: Uncaught (in promise): Error: Error in ./PageSingleComponent class PageSingleComponent - inline template:3:6 caused by: undefined is not an object (evaluating 'self.context.page.id')

This is my component:

import { Component, OnInit } from '@angular/core';
import { Page } from '../page';
import { PageService } from '../page.service';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-page-single',
  templateUrl: './page-single.component.html',
  styleUrls: ['./page-single.component.css'],
  providers: [PageService]
})
export class PageSingleComponent implements OnInit {

  page: Page;

  constructor( private pageService: PageService, private route: ActivatedRoute ) { }

  getPost(slug){
    console.log('page slug is',slug);
    this.pageService
      .getPost('other-page')
      .subscribe(res => {
        this.page = res[0];
         console.log('posts inside', res, slug);
      });
  }

  ngOnInit() {
    this.route.params.forEach((params: Params) => {
       let pageSlug = params['pageSlug'];
       this.getPost(pageSlug)
    });

  }
}

My Page Service:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Page } from './page';

@Injectable()
export class PageService {

  private _wpBase = "http://ecommerce-ux.london/wp-json/wp/v2/";

  constructor(private http: Http) { 
    this.http = http
    this.getPost().subscribe(
        (data) => {
          console.log('posts', data)

        },
        (err) =>  console.log("Error Loging In:",err),
        () => { console.log("All Good With The posts Data")  }
      );

  }

  getPages(): Observable<Page[]> {

      return this.http
        .get(this._wpBase + 'pages')
        .map((res: Response) => res.json());
  }

  getPost(pageSlug): Observable<Page> {

      return this.http
       .get(this._wpBase + `pages?slug=${pageSlug}`)
        .map((res: Response) => res.json());

  }

}

Page Single Component HTML:

<div>
  <!-- {{ page | json }} works -->
  <h1>{{ page.id  }}</h1>

</div>

Console.log https://i.sstatic.net/kHICT.png

Answer №1

The component's page property does not have a default value assigned to it, so it is not defined until the subscribe callback in PageSingleComponent.getPost sets it. This leads to an error because you cannot access the id property of an undefined value since it is not yet an object.

To solve this issue, you should delay evaluating the template expression until the page property has been set. This can be accomplished using either ng-if:

<h1 *ngIf=“page”>{{ page.id  }}</h1>

Or you can utilize the safe navigation operator:

<h1>{{ page?.id  }}</h1>

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

Tips for creating a login/registration system in a single page application

I've been working on a single-page application with ngRoute for navigation between tabs. Now, I need to incorporate a login and registration feature. After that, users should be able to access all the tabs. I'm unsure about the following: 1) Sho ...

Ways to generate data following the integration of Firebase Firestore in Vue.JS

How can I display the orders data retrieved from Firebase in my browser console? See the image link below for reference. https://i.sstatic.net/HPlaC.png This is the code snippet for fetching data from Firebase and displaying it in the console: orders(){ ...

What causes JavaScript Date to not update correctly during daylight savings time changes?

The Enigma of JS Dates My Initial Expectations In my Node applications, I have implemented functionality to send broadcasts to platforms like Facebook Messenger. Users subscribe to receive these broadcasts at a specific time, for example, 2pm daily. Whe ...

Exploring the data-* attribute in jQuery

Currently, I have a form structured as follows: <div data-role="page" data-last-value="43" data-hidden="true" data-bind='attr : {"name":"John"}'></div> My objective is to modify the name attribute from "John" to "Johnny". I am att ...

recording JSON requests in expressJS

Update: Apologies for the confusion, I have realized that I needed to move the app.use(express.logger('dev')); higher up in the program. This adjustment has resulted in logging every GET and POST request successfully. Express server now listeni ...

Retrieve the document from the HTTP response in NodeRed

Working with Node-Red, I'm facing a challenge wherein I need to retrieve a csv file through an API call. Upon making the http request, I received the following response: { "_msgid": "60d0351dcf215557", "payload": "&q ...

The commencement of setTimeout relies on my decision to halt the page's operation

During a form submission, my jQuery AJAX function is used to query the amount of data uploaded from a file. This information is then utilized in creating a progress bar. Here is an example of my JavaScript file: var formSubmitted = ''; var count ...

What methods can be used to disable a JavaScript function, such as utilizing hasClass()?

I am currently customizing a WordPress theme to load posts and pages using AJAX. I have successfully implemented this functionality with the code snippet below, but now I need to prevent the AJAX function from running when clicking on the logo that links t ...

Automatically resetting the Redux toolkit store when navigating between pages in Next.js

I am a new Next user who has been using Redux with React for a while. However, I encountered many challenges when trying to integrate Redux with Next. I have decided to move on from this solution. store.js import { configureStore } from '@reduxjs/to ...

Struggling with synchronicity in javascript(node.js) and seeking assistance

I am faced with a challenge in my express.js app where I need to execute a script on the server, followed by running a couple of functions to derive some values. The process should be sequential, but I am running into issues as JavaScript seems to move on ...

Leveraging next-generation JavaScript (NextJS), incorporate sass-loader for seamless inclusion of variables in each individual

I'm having trouble implementing a custom webpack configuration in my nextjs project. My objective is to automatically import @import "src/styles/variables.scss"; for all scss files in my application. I have successfully set up a webpack con ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

How can I connect ng-options to retrieve data from a remote JSON source?

Is it possible to use AngularJS to bind select options to a remote data source without needing an intermediate field? I'm not completely sure about this. For instance, the desired HTML would look like: <select ng-model="city" ng-options="obj for ...

Enhancing information on AngularJS

I'm relatively new to using AngularJS, and I'm struggling to find the right terms to search for. I have an HTML page that is connected to a controller. This page fetches data from MySQL. Within my controller, I have code like this to load the p ...

The validation process for the mongoose model failed due to incomplete input fields

Having trouble saving the submission model object with a one-to-one mapping with the Form and User models. submission.model.js const mongoose = require('mongoose') const Schema = mongoose.Schema const submissionSchema = new Schema({ form: { ...

Sorry, I am unable to provide the requested service as it involves rewriting content that is not owned by the

As a newcomer to Angular, I am working on an example from the developer guide to help me grasp the concepts. Here's the code I have so far, but I'm encountering an error that says: "TypeError: Cannot read property 'template' of undefine ...

what is the mechanism behind __dirname in Node.js?

Node.js is a new technology for me and I recently discovered the "__dirname" feature which is really useful for obtaining the absolute path of the script. However, I am intrigued by how it works and how it manages to interpret the directory structure. De ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

Implementing a specialized CSS handler for Node.JS

Currently, I have set up a Node.JS server for a new project at my workplace. As part of the project, I have created an optimizer function that removes unnecessary elements such as tabs, newlines, and comments from HTML, JavaScript, and CSS files. Strangel ...

Automatically update button appearance upon reaching zero value using JavaScript

Whenever I click the button, the user's HP decreases until it reaches 0 and then the button changes. However, a peculiar issue arises when the userHealth hits zero - the button does not change immediately. An additional click is required for the butto ...