Error message: "Trying to assign a value to a property that is not defined in Angular

I am encountering an issue while trying to set the reviews for an Angular 2 project. When I try to assign a value to this.reviews = targ, I receive an error message: TypeError: Cannot set property 'reviews' of undefined. However, I know that targ exists because I can successfully print it to the console. Any thoughts on why this might be happening?

import { ReviewService } from '../review.service';
import { Review } from '../review/review.component'
import { Component} from '@angular/core';
import {  OnInit } from '@angular/core';

@Component({
  selector: 'review-list',
  templateUrl: './review-list.component.html',
  styleUrls: ['./review-list.component.css'],
  providers: [ReviewService] //for the injector to be able to inject ReviewerService
})

export class ReviewListComponent implements OnInit {
   public reviews: Review[];

  constructor(private reviewService: ReviewService) {
    this.reviews = [] ;
  }


  initializeReviews(): void {
     this.reviewService.getReviews().then(
        this.set    
     ).catch(function(reason){
        console.log(reason);
     });

  }  



  set(targ):void {
    console.log(targ);
    this.reviews = targ;

  }

  ngOnInit(): void {
    this.initializeReviews();   
    //this.reviews = this.reviewService.get();
  }

}

Answer №1

When passing method references, the default behavior does not keep this pointing to the current class instance. To ensure that .this points to the correct class instance, you can use .bind(this) or arrow functions:


initializeReviews(): void {
   this.reviewService.getReviews().then(
      this.set.bind(this) // << add `.bind(this)` or
      // (val) => this.set(val)    
   ).catch(function(reason){
      console.log(reason);
   });
}

Answer №2

If you pass the method like that to the promise, you risk losing the context of 'this'. To avoid this issue, make sure to either wrap the method in an anonymous function or bind the correct context.

initializeReviews(): void {
   this.reviewService.getReviews().then((response) => {
       this.set(response);
   })
   .catch((reason) => {
    console.log(reason);
   });
} 

Alternatively, you can use

this.reviewService.getReviews().then(this.set.bind(this))
to maintain the proper context.

It’s important to note that using the function keyword inside a TypeScript class can also lead to loss of the 'this' context.

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

Updating components in Angular4 when route changesHow to update components on route

How can I ensure my component updates when the route changes? Here is the code for my component : import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ListService } from '.. ...

When running the command "ng build --prod" in Angular 5, you may encounter an error stating

My project runs smoothly when I use ng serve locally. However, when I run ng b -prod, I encounter the following error: ERROR in app\logged-in\content\routing\routing.component.ts(9,16): Error during template compile of 'Routing ...

Using TypeScript to conditionally type input arrays

My goal is to create a function that accepts an array of variables that can belong to a few different types. For each specified type, the second argument (callback) of the function will receive an array of corresponding types. The relationship is such th ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

The "isActive" value does not share any properties with the type 'Properties<string | number, string & {}>'. This issue was encountered while using React with TypeScript

I'm attempting to include the isActive parameter inside NavLink of react-router-dom version 5, but I'm encountering two errors. The type '({ isActive }: { isActive: any; }) => { color: string; background: string; }' does not have an ...

The function res.status is not defined

Currently, I am in the process of integrating my upcoming app with Google Sheets. I have relocated the function that manages the post request to "app/api/sheets" as per the recommended documentation. import type { NextApiRequest, NextApiResponse } from &ap ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

What is the best way to correctly link each object from a for loop to its corresponding DOM element?

I'm looking for a solution that resembles the following code snippet: <select> <option [bound]="items[i]" *ngFor="let item of items; #i = index">{{item}}</option> </select> ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

What is the process for determining a variable's type programmatically and then utilizing it as the type for a function parameter?

I have a question regarding TypeScript version 4.1.5. Let's consider the scenario where I am making a GraphQL query in a function called getItems. The result, items, inherits an unnamed generated type from this function. Now, I need to perform a map ...

Populating datasets with relative indexing

I am working on a code where I need to fill the datasets with the property isProjected set to 1. There are 3 datasets - lower estimate, projected, and upper estimate. The goal is to fill the Lower Estimate and Upper Estimate with a background color of rgba ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

How can I invoke the header component function in another component using Angular 2?

Is there a way to invoke the showmodel(displayType) function from another component? How can I call a function in the header component from a different component? header.component.ts import { Component,Renderer } from '@angular/core'; i ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

Tips for accurately implementing the onHoverIn TS type in the React Native Web Pressable component

I'm working with React Native Web and Typescript, and I want to integrate the React Native Web Pressable component into my project. However, I encountered an issue where VSCode is showing errors for React Native Web prop types like onHoverIn. The pro ...

Enhance Ng2-smart-table with a custom rendering component

I am attempting to implement a custom Renderer component in my ng2-smart-table, but I keep encountering the following error message. No component factory found for undefined. Have you added it to @NgModule.entryComponents? at…, …} What's baf ...

A guide to positioning the content of an Angular tag within a span element

Can someone help me figure out how to properly align the PO number and Vendor information on my page? from PO Number: 344 Vendor: yu PO Number: 3445 Vendor: yu PO Number: 344 Vendor: yu to PO Number: 344 Vendor: yu PO Number: 3445 Vendor: yu PO Num ...

Angular: a technique for creating customized error messages and modifying fields

When an error occurs in a form, the text fields are cleared and the errors are set as shown below switch(result){ case "SUCCESS": // handle success case case "ERROR1": this.Form.controls.text1.setValue(''); ...