How can we access class variables using "this" in Angular 2 TypeScript?

I am struggling to access the object "sessions" in this code snippet. The problem seems to be that "this" is null:

/// <reference path="chrome/chrome-app.d.ts" />

import { Component, Input, OnInit } from '@angular/core';
import { AppService } from './app.service';

@Component({
    selector: 'tabs',
    templateUrl: './templates/app.html',
    providers: [ AppService ]
})

export class AppComponent implements OnInit {
    public sessions : Object;
    constructor( private appService : AppService ) {}

    getBookmarkLists() {
        console.log(this.sessions) // it gives undefined
        this.sessions['test'] = 'yea'; // it fails
        this.appService.getBookmarks().then(function(bookmarks : any) {
            console.log(this.sessions) // it fails
        });

    }

    ngOnInit() {
        this.getBookmarkLists();
    }
 }

I hope to successfully access the variable and populate it as intended.

Answer №1

The Sessions object has not been initialized anywhere in your code. It should be done like this:

export class AppComponent implements OnInit {
    public sessions: Session[] = []; // Make sure to initialize it here
    constructor( private appService : AppService ) {}

    getBookmarkLists() {
        console.log(this.sessions) // It should not return undefined
        this.sessions['test'] = 'yea'; // This line should not throw an error
        this.appService.getBookmarks().then((bookmarks : any) => {
            // Use an arrow function or bind the function properly to avoid incorrect 'this' reference
            console.log(this.sessions) // This should work fine
        });

    }

    ngOnInit() {
        this.getBookmarkLists();
    }
}

The crucial part is initializing sessions = [];. Thus, the issue with this referencing the class instance in methods will also be resolved.

Ensure that the callback passed to the then method is an arrow function and not a traditional function to maintain the correct reference of this to the class instance.

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

Struggling to send the correct array in response to an HTTP request. Is there a way to efficiently send results from a function using expressjs?

Issue Summary: Currently, I am facing a challenge while working on a software program that relies on an SQL database at the backend and utilizes the npm SQLite3 module for communication purposes. The problem arose when performing an HTTP request to the ser ...

Is it a cause for concern that SWR reveals client-id and Bearer tokens with each API call?

After building an application using NextJs, NextAuth, and SWR, I encountered a concern. I utilize SWR to call multiple Twitch APIs, authenticating with my Twitch applications Client-Id and the user's Bearer token from the NextAuth session object. The ...

The mat card doesn't quite align with the rest of the page

I am currently utilizing Angular Material and Bootstrap in my project. My aim is to display a mat-card that fits perfectly on all screen sizes. However, I am encountering empty spaces on the right side of the card. While it fits properly on some screen ...

Activate real-time highlighting by clicking on the search button

I created a simple program that searches for a value within a div and displays the first location of the word. However, I am looking to enhance it by highlighting all repeated locations of the searched word after pressing the search button. <html> & ...

Django has the capability to manage ASGI/HTTP connections, but it does not support websockets

Hello, I am encountering an error. Despite trying various methods and researching previous discussions here, I cannot seem to resolve the issue. Whether I use daphne or uvicorn, the result remains the same - it works locally but fails on the server with t ...

A tutorial on making a POST request using axios in a React application

I am struggling with my JavaScript skills I need assistance with calling the following CURL command successfully: curl -X POST -H "Content-Type: application/json" -u john.doe:moqui -d "{\"firstName\":\"Hung&bso ...

Ajax successful event fails to trigger

Having Trouble Implementing Okta Authentication with WebForms The login functionality is working, but the redirect part is not functioning correctly I have attempted to use void and return a JSON object/string, but it does not seem to work If I remove th ...

The parameter 'data' is assumed to have an 'any' type in React hooks, according to ts(7006)

It's perplexing to me how the 7006 error underlines "data," while in the test environment on the main page of React Hooks (https://react-hook-form.com/get-started#Quickstart), everything works perfectly. I'm wondering if I need to include anothe ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

Exploring the differences between using a local controller in Angular's MdDialog modal versus displaying a shadow at

I've been attempting to utilize an app-level controller to showcase a modal dialog. The local function controller tests are functioning flawlessly, but the app level controller is only showing a grey shadow instead of the expected dialog. The edit an ...

Guide to routing within the same component in Angular?

In the scenario where I have multiple lists of users with IDs such as (1, 2, 3, 4, 5...), the desired functionality is that upon clicking a button, the details for each respective user should be displayed. For example, clicking on the first user's det ...

What is the best way to convert a JSON string from a specific array into an array object?

JSON object: { "data": { "myStatus": "[1 2 21 0 50 0 0 0],[2 1 3 1 50 0 0 0]" }, "success": true } Upon converting to the JSON object, it appears that the myStatus is being treated as a string. The goal is to parse it as an Array inst ...

Sort the array elements by a specific property while preserving the original order of the array

I created a function that can group an array by one or more properties: var groupBy = function (fields, data) { var groups = {}; for (var i = 0; i < data.length; i++) { var item = data[i]; var container = groups; for (va ...

Tips for downloading a file in React using raw file data

I've been struggling with a particular issue for the past couple of days and just can't seem to find a solution. It involves retrieving data from an API on our outdated system related to Attachments and other information. When I execute the query ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

How can you refer to the implementing class from an interface in TypeScript?

Delving into the Typescript type system, I am currently working on implementing the Fantasy Land Spec and encountered a hurdle while trying to implement the specification for Semigroup. The spec dictates that a Semigroup must follow the type definition ou ...

AngularJS: Encountering an unexpected identifier while trying to make a POST

I'm facing an issue with my http POST request in AngularJS. When I make the function call to $http, I receive a SyntaxError: Unexpected identifier. The unexpected identifier is pointing to the line url: 'rating-add' within my $http call. ‘ ...

Updating an AngularJS scope variable without the need for redundant re-repetition

Currently, I am facing an issue where I am assigning items to the scope like so: $scope.items = [{ name: 'one', value: 1 }{ name: 'two', value: 2 }] I am using ng-repeat to display these items. There's a service that ...

Increasing several array elements within a MongoDB object

I have been struggling with this problem for some time now. My goal is to update multiple array values in the same object with a single query. The data in the database appears as follows: id: 616f5aca5f60da8bb5870e36 title: "title" recommendations: ...

Conceal the galleryView plugin seamlessly without the need for a

I have implemented jQuery on my webpage to load content without refreshing, displaying only the necessary information. Within the gallery section, there are links for "Other Photography" and "Nude Art". Clicking on these links initializes the gallery with ...