Angular 2: variable turns null

One issue arises where the property passed to the view child appears as undefined:

Parent Component:

@Component({
    selector: 'app-searchbox',
    template: `
            <app-artifact-list [artifacts]="searchResults"></app-artifact-list>
    `
})
export class SearchboxComponent implements OnInit {

    // Initialize the property explicitly
    // Same effect as initializing in constructor
    searchResults: Artifact[] = [new Artifact()];

    constructor(private artifactService: ArtifactService) {
    }

    ngOnInit(): void {
        this.pollService(this.artifactService.findByQuery('guice'));
    }

    private pollService(request: Observable<Artifact[]>) {
        return request.subscribe(this.fillInResults);
    }

    private fillInResults(result: Artifact[]) {
        result.forEach(console.log);
        for (let obj of result) {
            // Issue when trying to push into undefined this.searchResults
            this.searchResults.push(obj);
        }
    }

}

Child Component:

@Component({
    selector: 'app-artifact-list',
    template: `
            <h1>{{_artifacts | json}}</h1>
     `
})
export class ArtifactListComponent implements OnChanges {

    private _artifacts: Artifact[] = [];

    ngOnChanges(changes: SimpleChanges): void {
        console.log('Property changed');
    }

    @Input()
    set artifacts(artifacts: Artifact[]) {
        console.error('Property changed');
        this._artifacts = artifacts;
    }

}

Initially, during the constructor call, the property initializes correctly but becomes undefined in the callback method.

Could this be somehow linked to this? Maybe this.searchResults references something else in the callback?

Answer №1

After conducting some research on the usage of this within the context of "function references," I discovered that this actually refers to a different object. JavaScript never ceases to amaze me :)

Here is a workaround:

private pollService(request: Observable<Artifact[]>) {
    return request.subscribe(
        this.fillInResults.bind(this)
    );
}

private fillInResults(result: any) {
    result.forEach(console.log);
    for (let obj of result) {
        this.searchResults.push(obj);
    }
}

Alternatively, you can use fat arrow functions:

private pollService(request: Observable<Artifact[]>) {
    return request.subscribe(
        result => this.fillInResults(result)
    );
}

private fillInResults(result: any) {
    result.forEach(console.log);
    for (let obj of result) {
        this.searchResults.push(obj);
    }
}

For further explanation, please refer to this question: Angular2 component's “this” is undefined when executing callback function

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

Reach out to the property via phone if it is listed in the JSON

When receiving JSON data from the server, I come across two different structures: JSON 1: { [{ name : 'sample1', code:'sample code 1', data : { display :'test' } ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

Tips for excluding a key in object literal notation when the value of the key is undefined

Currently, I am developing an RPG character generator that utilizes Redux. Within my reducer function, I aim to have the ability to update gear modifications and keep track of these changes. These modifications may include a rating, although it is not mand ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...

Initiate conversation with QnA Maker Bot Framework recognizer (Node JS)

Is it possible to pass a "Welcome Message" at the start of a chat with a bot using QnA Maker recognizer in a way that the model does not interpret it as a message to be sent to the model? I am currently working with the latest Node.js API. var intents = n ...

You may encounter an error stating "The requested resource does not have the 'Access-Control-Allow-Origin' header" accompanied by an Uncaught SyntaxError saying "Unexpected identifier."

Exploring an AJAX Call var response = ""; //Making an Ajax call to the database server var target_url = "http://SomeIP/db/*create_table*?token=1234qwer&table_name="+table_name+"&array_of_fields={"+final_fields+"}"; function hit_db(callback) { ...

Configuring the baseUrl for Axios in a Vue.js application triggers the sending of a request

I have encountered an issue in my app where Axios automatically makes a request to the baseUrl without me explicitly making one. This occurs even when the app is loaded in the browser. In my main.js file, I have set the baseUrl using: axios.defaults.baseU ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...

What is the best way to retrieve a particular variable from an ng-repeat loop?

I'm currently working on a task where I have an ng-repeat loop that generates multiple dropdowns. Each dropdown is associated with a unique ID generated by the controller for reference purposes. The issue I am facing is that when a user selects an op ...

Handling MySQL insertIds and errors in Node.js using MySQL is a crucial aspect of

I am struggling to handle errors and retrieve the insertId after creating a new row in my database using code from the official page of mysqljs/mysql. How can I modify my code to achieve this? var post = {deviceImei: deviceInformation.deviceImei, created_ ...

How to pass data from a child component to a parent component in React applications

In my search component, I need to pass a variable called "apiUrl" to the parent component. While I have successfully handled events for other parts of the code, I am unsure how to manage this specific variable transfer. The goal is to send the dynamically ...

Unable to input characters consecutively into the text field because it is being displayed as a distinct function within the component

When attempting to bind a text field using the approach below, I encounter an issue where entering characters in the text field causes the control/focus to shift out of the field after the first character is entered. I then have to click back into the text ...

Tips for closing the modal after a SetTimeOut event and postback have happened

On my web page, I have a textbox for email and a submit button that triggers an email to be sent. Since this process takes some time, I decided to show the user a modal window with a loading panel while the email is being sent. However, after waiting for t ...

Three.js: placing objects at the top of the screen with consistent dimensions

As a newcomer to three.js, I am unsure if my question falls into the category of beginner or advanced. I am looking to place objects in the top left corner of the screen, with each subsequent object positioned to the right. It is important that each object ...

Preserve a retrieved value from a promise in Angular

Upon loading the page, the dropdown menu is populated with various values (such as 1, 2...7). However, when attempting to set a specific value based on a certain condition within a promise, it doesn't seem to work. How can this issue be resolved? htm ...

Retrieve the value attribute of the <li> element

For a school project, I am working on a small website where I need to iterate over an array populated by an SQL query. The data will be displayed in the following format: <ul class="list-group"> <li class="list-group-item" name="id" value="36 ...

The issue with Angular 1.6 not displaying the scope value in the template

Hey there! I'm currently working on index.html Here's the code snippet from before: <body ng-app="MainController"> <div class="page page-base {{ pageClass }}" ng-view> </div> </div> Then, I made changes by ass ...

What is causing the image to become distorted on the canvas?

Despite specifying the image dimensions to be 50px by 50px, it appears stretched on the y-axis like this. View Stretched Image I suspect that the issue lies with the CSS styling applied. Here is my current CSS code: canvas { background-color: green; ...

How to covert a div to a PDF in reactJS without displaying it on the webpage

Here is a function using jsPDF to create a PDF. The issue I am facing is that the div which needs to be converted into a PDF should not be visible on the webpage. If I use 'hidden' in the div, it results in a blank PDF. function generatePDF() { ...

Using AngularJS to transclude ng-repeat within a directive

I have created a custom directive that transcludes the original content, parses it, and uses the data in the original content to construct the new content. The main concept behind it is as follows: .directive('customList', function() { retur ...