Error: Attempting to assign a value to a property that is not defined - Uncaught TypeError: Unable to set the property 'other_user_image

I've been struggling to set the image src attribute using a typescript function, but I keep encountering a "cannot set property of undefined error." It's frustrating because I can't seem to figure out where I'm going wrong.

Here is the HTML code snippet:

<div class="panel-heading" style="border-bottom: 1px solid #cfdbe2; padding: 14px 15px;">
    <div class="pull-left">
        <img class="media-box-object img-circle thumb32" src="{{other_user_image}}" alt="Image" />
    </div>
    <div class="panel-title">User</div>
</div>

And here is the TypeScript component.ts code snippet:

export class ChatComponent implements OnInit {
    other_user_image: string;

    constructor(
        public authService: AuthService,
        afAuth: AngularFireAuth,
        public db: AngularFirestore,
        private router: Router) {}

    ngOnInit() {
    }

    openChatWindow(event: any){
        var target = event.target || event.srcElement || event.currentTarget;
        var idAttr = target.attributes.id;
        var value = idAttr.nodeValue;
        // var elem_id = (this.elem);
        console.log(value);
        var user_chat_room = this.db.collection("users").doc(value)
        console.log(user_chat_room);
        user_chat_room.ref.get().then(function(documentSnapshot) {
            console.log(documentSnapshot.data());
            if (documentSnapshot.exists) {
                console.log('doneeeeeeee');
                console.log(documentSnapshot.data()['profileImageUrl']);

                this.other_user_image = documentSnapshot.data()['profileImageUrl'];
                console.log(this.other_user_image);
            } else {
                // doc.data() will be undefined in this case
                console.log("No such document!");
            }
        });
    }
}

Even though I am able to print

documentSnapshot.data()['profileImageUrl']
as a valid URL like
http://qualiscare.com/wp-content/uploads/2017/08/default-user.png
, I am struggling to assign it to the image src attribute.

Answer №1

The issue lies in using this within a function declared with function () {...}. In this scenario, this becomes undefined, resulting in an error.

To resolve this, switch to an arrow function which maintains the context of this (referring to your component):

ngOnInit() { }

openChatWindow(event: any){
        var target = event.target || event.srcElement || event.currentTarget;
        var idAttr = target.attributes.id;
        var value = idAttr.nodeValue;
        // var elem_id = (this.elem);
        console.log(value);
        var user_chat_room = this.db.collection("users").doc(value)
        console.log(user_chat_room);
        user_chat_room.ref.
            get().then(documentSnapshot => {
                console.log(documentSnapshot.data());
                if (documentSnapshot.exists) {
                    console.log('doneeeeeeee');
                    console.log(documentSnapshot.data()['profileImageUrl']);

                    this.other_user_image = documentSnapshot.data()['profileImageUrl'];
                    console.log(this.other_user_image);

                } else {
                    // doc.data() will be undefined in this case
                    console.log("No such document!");
                }
            });
}

Pay attention to the get().then(...) line.

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

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

Fix the problem of "@typescript-eslint/no-invalid-this" in class fields without causing issues with "@typescript-eslint/no-this-alias"

Take a look at the code snippet below: import { Vue, Component } from "vue-property-decorator"; @Component({ components: {} }) export default class ProductViewingAndEditingPage extends Vue { private readonly componentsReferencesIDs: { ...

Proper method of managing undeclared declaration files (index.d.ts)

I encountered the following error message: error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'an ...

Loading Highcharts in Angular app

I'm currently using a highchart donut chart, but it's loading before the API response comes in. This is causing the data not to render properly. I need to retrieve the value of this.Total_connect in the highchart. Also, I want to access the val ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first. Is there a way to automatically trigger another observable when a specific ...

What is the reason for this error message: The 'filter' property is not found on type 'Films'?

Could use some help with PrimeNG integration in my app as I've encountered a persistent error. I'm aiming to implement a delete function using confirmationDialog. Below is the excerpt from my component.ts file: export interface Films { id?: a ...

Unable to view console log output within the loop

I am having trouble accessing console logs in my application when trying to loop through the data set provided below. The code snippet includes a function for calculating AVAF loan adjustments, but for some reason, no data is being printed to the console. ...

Tips for adding an item to an array within a Map using functional programming in TypeScript/JavaScript

As I embark on my transition from object-oriented programming to functional programming in TypeScript, I am encountering challenges. I am trying to convert imperative TypeScript code into a more functional style, but I'm struggling with the following ...

What steps should I follow to dockerize my Angular application for production deployment?

I have been attempting to containerize my current Angular application using Docker. Here are the details: App Name: admin-dashboard nginx.conf Dockerfile Operating System: Ubuntu 18.03, docker is up and running. This is my Dockerfile: ### STAGE 1: Bui ...

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

Angular 2 + Meteor already has a "collection" in its repository

import {Mongo} from 'meteor/mongo'; export let Products = new Mongo.Collection('products'); This code snippet is part of my sample project. However, when I attempt to run the project, an error is thrown. The error message reads: "Th ...

The map buttons are located underneath the map, and unfortunately, it seems that setting the map height to 100% using Angular is

Upon completing the creation and display of the map, an unusual occurrence is taking place where the map buttons ("Zoom rectangular, map settings, and scale bar") are appearing below the map as oversized icons. Additionally, there is a challenge when setti ...

Creating a fresh line using text interpolation within Angular 4 and Ionic 3

I am facing an issue with my front-end code: <p>{{ news.content }}</p> The variable news.content is stored in the Firebase DB. Is there a way to insert a new line in this text interpolation without making any changes to the front-end code (H ...

What steps can be taken to establish an array type that is limited to predefined values?

I am currently working on defining a type for an array that requires specific values to be present in a certain order at the beginning of the array. type SpecificArray = ('hello'|'goodbye'|string)[] // Current const myArray: SpecificAr ...

How to initiate a refresh in a React.js component?

I created a basic todo app using React, TypeScript, and Node. Below is the main component: import * as React from "react" import {forwardRef, useCallback, useEffect} from "react" import {ITodo} from "../types/type.todo" import ...

Is it possible for a const type parameter to capture varargs?

TypeScript 5.0 has recently introduced a new feature known as const type parameters. Can varargs be captured using this type parameter? Let's take a look at the following function attempting to achieve this: function insertIf<const V extends any[] ...

I'm looking to create a card carousel using HTML and Bootstrap, but for some reason, the cards are not aligning properly and are stacking

I need assistance with creating cards in a loop at runtime. However, the cards are displaying vertically aligned to each other instead of horizontally as intended. I have already tried using col-md-4 but it did not work. enter code here <div class=&q ...

Passing data from Angular 2 to a modal component

Within my app component, I have implemented a table that triggers a modal to appear when a user clicks on any row. The modal displays details related to that specific row. The functionality is achieved through the following HTML code within the component c ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...