The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I properly utilize the on method of the Firebase database to bind the data? The error occurs at { this.singlePost.content = snapshot.val();}, stating that it cannot read the value of singlePost.content because it is null.

export class BlogDetailComponent implements OnInit {

  singlePost: Blog;
  id: any;

  constructor(private route: ActivatedRoute, private router: Router) {
    let contentUpdated: any;
  }

  ngOnInit() {
    let postId = this.route.snapshot.params['id'];
    this.getSingle(postId);
    this.id = postId;
    let starCountRef = firebase.database().ref('blogPosts/' + this.id + '/content');
    starCountRef.on('value', function (snapshot) {
      if (snapshot.val() != null) {
        this.singlePost.content = snapshot.val();
      }
    });
  }

  getSingle(id: string) {
    let dbRef = firebase.database().ref('blogPosts');
    dbRef.orderByChild('id')
      .equalTo(id)
      .once('value')
      .then((snapshot) => {
        let tmp = snapshot.val();
        let transform = Object.keys(tmp).map(key => tmp[key]);
        let title = transform[0].title;
        let content = transform[0].content;
        let imgTitle = transform[0].imgTitle;
        let img = transform[0].img;
        this.singlePost = new Blog(title, content, imgTitle, img);
      });
  };
}

The code runs correctly with the following adjustments:

export class BlogDetailComponent implements OnInit{

    singlePost : Blog;
    id : any;

    constructor(private route : ActivatedRoute, private router : Router) {
      let contentUpdated : any;
    }

    ngOnInit() {
      let postId = this.route.snapshot.params['id'];
      this.getSingle(postId);
      this.id = postId;
      let starCountRef = firebase.database().ref('blogPosts/'+this.id+'/content');
      starCountRef.on('value',function(snapshot){
        if(snapshot.val() != null )
        { console.log(snapshot.val());}
      });

    }

    getSingle(id : string){
      let dbRef = firebase.database().ref('blogPosts');
      dbRef.orderByChild('id')
      .equalTo(id)
      .once('value')
      .then((snapshot) => {
        let tmp = snapshot.val();
        let transform = Object.keys(tmp).map(key => tmp[key]);
        let title = transform[0].title;
        let content = transform[0].content;
        let imgTitle = transform[0].imgTitle;
        let img = transform[0].img;
        this.singlePost = new Blog(title,content,imgTitle,img);
      });
    };
  }

Answer №1

When working with callback functions, it's best to utilize Arrow function/Lamba for accessing the correct this (context).

starCountRef.on('value', (snapshot: any) => {
    if (snapshot.val() != null ) { 
        this.singlePost = {content : snapshot.val() };
    }
});

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

Exploring the zorro components (nz-tree) in Angular for effective testing with Jasmine and Karma

How can I access the data in the $event and verify if the treeClick method is being called upon click? When running the test file, I encountered the following error: "Expected spy treeClick to have been called once. It was called 0 times." In t ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on: if (validateField(document.forms[0].name) == false) { isValid = false; } if (validateField(docume ...

Learn how to showcase the URL path of an image stored in MongoDB on the front end of a website with the help of Node

I've managed to save the image paths of the uploaded pictures. They are stored like this http://localhost/public/Images/okro.jpg. However, I'm unsure how to retrieve them from the database and showcase them on the frontend. Is there a method to ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

Next.js application encounters XMLHttpRequest ReferenceError when attempting to retrieve firebase storage file URL

I have successfully set up a Next.js (11) app with a functional connection to Firebase version 8.7. I am facing an issue when trying to retrieve the download URL for an image: If I create a function like the one below to fetch the uploaded image - assumin ...

"The Node.js program is unable to access the contents of the browser.js file when loaded in

After spending an unreasonable amount of time trying to debug this issue, I am still unable to resolve it. Currently, I am following a udemy tutorial where the instructor implements the same code provided below. However, despite my efforts, the code is not ...

Creating a dynamic form with Angular 5 that includes a conditional required textarea

When the checkbox is clicked, a textarea will appear and is required [required]="otherVendorsChecked == true ? true : false". Even if I select the checkbox and then deselect it, the textarea input remains required. Any ideas on what could be going wrong? ...

Do you think this architecture is ideal for a NodeJS recursive MongoDB archiver?

Currently, I am faced with the challenge of archiving data stored on a MongoDB server that has been operational for more than a year. The server has accumulated close to 100GB of data, with many collections containing over 10 million documents each. Unfort ...

Issue downloading file in Angular using Filesaver.js is causing problems

I am utilizing Filesaver.js to attempt downloading files from my Express (NodeJS) backend. Below is the backend code responsible for file downloads. It incorporates a middleware to authenticate the request. res.download(url, function (err) { if (err) ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

Tips for resetting and enabling file uploads with ng2-file-upload

My file upload functionality is working smoothly using ng2-file-upload. However, I am facing a challenge in handling server-side errors and resetting the file uploader. How can I achieve this? Below are the snippets of code that I am currently using: HTML ...

Steps to authenticate against a Web API in an Angular application without requiring a traditional login process

My setup involves an Angular Application and a Web Api. Previously, all users were routed to the login page upon accessing the app, where a token was created using their credentials for authentication purposes. Now, however, it is no longer mandatory for ...

Building a jQuery function to filter JSON data based on user input without relying on any external filter

Is it possible to dynamically filter a list of JSON data based on the value entered in a search input box for a specific key, such as 'firstname'? I am new to JavaScript and jQuery and would appreciate any help. HTML <input type="search" nam ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

How can I verify if my discord.js bot has the necessary permissions from a server or channel?

I need to verify two things: Determine if my bot has a particular SERVER permission (return true/false based on the presence of that permission) Confirm if my bot possesses a specific CHANNEL permission (return true/false depending o ...

Disabling the global ajax datatype causes issues with Rails remote links

I have successfully developed a rails application that submits a form remotely and then displays form validation errors if the validation process fails. The form itself is working perfectly. However, I've come across an issue where the way I've ...

Toggle visibility of various items in a to-do list, displaying only one item at a time with the use of JavaScript

I am currently working on a web project using the Laravel framework. I am struggling with implementing a feature where only the title of each to-do item is displayed, and when clicked, it should reveal the corresponding content. However, I have encountered ...

What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if ev ...

What is the best way to showcase information from multiple JSON files simultaneously?

Creating dynamic JSON URLs based on browser cookie data. var cookie = $.cookie('faved_posts'); The cookie contains IDs like 123456, 111111, 000001, etc. Now we need to request the JSON file for each ID in the cookie. We have: $.each(cookie, ...