What is causing the undefined value for the http used in this function?

  • My Code Component

    import { Component, OnInit } from '@angular/core';
    import { Http } from '@angular/http';
    
    @Component({
      selector: 'app-root',
      template: '<button id="testBtn"></button>'
    })
    
    
    export class MarketComponent implements OnInit {
    
      constructor( public http: Http ) { } 
    
      ngOnInit() {
    
        let btn = document.getElementById("testBtn");
          if(btn){
            btn.addEventListener('click',
    
              function(){
    
                this.http.get('./test.json')
                .map(response=>response.json())
                .subscribe(
                  data => { //success
                    console.log("success");
                  },
                  error => console.log("HttpRequestButton Error"), //error
                  () => console.log("CategoryCount HttpRequestButton Get Test Finish")
                );
    
              }
            );
          } // if end
    
        }
      }
    

I am curious...

I attached the Click event to the addEventListener method.

Why is the http object undefined inside the function? I am unsure of the cause.

I need to access http within the function. Is there a solution?

Answer №1

your solution

 btn.addEventListener('click',
          function(){
            this.http.get('./test.json')

Needs to be updated to

 btn.addEventListener('click',
          () => {
            this.http.get('./test.json')

For more information, visit:

Answer №2

This 'this' is not the 'this' you're looking for. Consider using an arrow function or calling bind(this) at the end.

 const fetchData = () => {

        this.http.get('./test.json')
        .map(response=>response.json())
        .subscribe(
          data => { //success
            console.log("success");
          },
          error => console.log("HttpRequestButton Error"), //error
          () => console.log("CategoryCount HttpRequestButton Get Test Finish")
        );

      }.bind(this)

In a better approach, it could be implemented like this :

@Component({
    selector: 'app-root',
    template: '<button (click)="onClick()"></button>'
})

export class MarketComponent implements OnInit {

    constructor( public http: Http ) { } 

    ngOnInit() {}

    onClick(){
       this.http.get('./test.json')
        .map(response=>response.json())
        .subscribe(
          data => { //success
            console.log("success");
          },
          error => console.log("HttpRequestButton Error"), //error
          () => console.log("CategoryCount HttpRequestButton Get Test Finish")
        );

    }

}

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

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

Convert a Java library to JavaScript using JSweet and integrate it into an Angular project

Just recently, I embarked on my journey to learn TypeScript. To challenge my newfound knowledge, I was tasked with transpiling a Java library using JSweet in order to integrate it into an Angular project. This specific Java library is self-contained, consi ...

Ways to reuse test cases across different test suites in Protractor

There are some shared test cases that can be utilized across different test suites. For example, suppose suite x and suite y both require the same set of test cases to function properly. To address this, a separate .js file containing the shared code has ...

The module 'json-stringify-safe' could not be located

Encountering an issue while executing the command - ionic serve The code was functioning properly on a different system but seems to be causing trouble for me at the moment. https://i.sstatic.net/X1JG0.png ...

Ways to immediately display an uploaded image as the background on a canvas

Using TypeScript, I am attempting to set an uploaded image as the background of a canvas. However, I am facing an issue where the image only loads properly after the user has uploaded it two times. How can I ensure that the image has finished loading befor ...

The response type for HTTP Get in Typescript is specified as "text"

I'm currently working on a Typescript HTTP Get request and need to customize the response type as text. Here's my code snippet: getMessageContent(messageContentId?: string): Observable<string> { const url = this.commonService.getApi ...

Issue with the rendering of Navigation Bar in Angular 4 Bootstrap alpha

I am currently working on integrating Bootstrap 4 into my Angular 4 application by following a tutorial. However, I have encountered an issue with the navigation bar not functioning correctly. https://i.sstatic.net/92phM.png After taking the necessary st ...

Tips for successfully sending an array of numbers using TypeScript and React

Exploring Types in React is new to me and I'm still navigating my way through it. My current challenge involves adding numbers from a form within a child component to an existing array of numbers. To tackle this, I've initialized a useState hoo ...

data is currently being uploaded to the storage, however, the grid is not displaying any

After loading JSON data into the store, I am unable to see any data in the grid. Can someone please point out what I might be doing wrong? Here's the code snippet for the grid: { xtype: 'gridpanel', ...

The TypeScript find() method on an array are showing an error message that says, "There is no overload that matches this call

Issue Description I encountered a problem while using TypeScript's find() method for an array. Whenever I input a value, it does not work properly and displays an error message stating, "No overload matches this call". Code Snippet addOption(event: ...

Using POST parameters with HTTP Client in Angular 2

I have been working on converting my jQuery code into Angular2. While the jQuery code is functioning correctly, the Angular2 code seems to be producing a different output from the API. I have already compared the parameters and endpoint using firebug/cons ...

Getting a response directly from an HttpRequest and assigning it to a variable

Can someone help me with this issue: // api-service.ts fetchUsers() { return this.http.get(this.BaseUrl + 'users/', httpOptions); } I am trying to assign the result of this API call to a variable like so : // users-component.ts ngOnInit() ...

An issue has been identified with React's HTML input maxLength feature where it does not display an error

Within my form, I have an input field that currently does not include validation for a maximum length. <input type="text" className="form-control" id="company" onBlur= ...

What is preventing me from including an additional parameter in a function in TypeScript?

I am currently developing a task management application. I am facing an issue while attempting to incorporate the event and items.id into a button function for actions like delete, edit, or mark as completed. While this functionality works smoothly in pla ...

Automatically assign the creation date and modification date to an entity in jhipster

I am currently working on automatically setting the creation date and date of the last change for an entity in JHipster, utilizing a MySQL Database. Below is my Java code snippet for the entity: @GeneratedValue(strategy = GenerationType.AUTO) @Column(nam ...

Encountering an error when trying to set data in a Firestore document with a customized JavaScript object: "Invalid data provided for function DocumentReference.set()"

For my initial project, I need help in identifying where the issue lies. Firstly, I have a function that adds data to Firebase: addpost() { let newposts = new Posts( this.addForm.value ) this.postsservice.addPosts(newposts); } Ne ...

Transform Angular into a library

I've been exploring different options but still haven't nailed down the best approach. I've developed an Angular library with custom components, which I'm converting into Web Components to be used in non-Angular applications. But to mak ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Encountering the "Argument of type 'string' is not assignable to parameter of type 'never'" error when using Array.prototype.includes

The data type for keys is a combination of string[] | number[], which is derived from the ID type. The data type for id is simply ID. We want to check if the id exists within the array of keys. import React, { useState } from 'react'; type Distr ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...