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

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

How to use the Angular 7 CLI in a programmatic way

My goal is to set up a server that can launch an Angular 7 app. Another scenario where this capability would be useful is for more advanced generation tasks, such as adding multiple files directly after generating an Angular project. const angularClient = ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

Include a hash in the URL when the current location is entered into the view by scrolling

In my current situation, I am required to implement a @HostListener in order to navigate to an element within my web page: @HostListener('click', ['$event']) onClick(e: any) { e.preventDefault(); const href = e.target.getAttri ...

Tips for maintaining consistent column size in an angular material table as the screen size shrinks

I have a material table with 9 columns and I want to keep the column size consistent even when the screen size is reduced. Currently, as I decrease the screen size, the last column shrinks first while the other columns remain the same size, creating an un ...

What is the best way to extract Angular's routing UrlMatchResult from UrlMatcher within a component?

Having trouble with routing in Angular 10. Trying to include a token in my URL that can contain various quantities of / characters. To prevent Angular routing from getting confused, I followed the advice on this post and decided to implement the UrlMatcher ...

Attempting a second filter of the table using the dropdown results in no data being returned

I've developed a CRUD app using Angular 7, and I'm facing an issue. When I select a dropdown item for the first time, it shows the desired table data. However, on selecting another item for the second time, it returns nothing. Below is my compone ...

Guide for setting up various validations for formGroup in an Angular 5 project

I am currently working on implementing Angular reactive form validation. My existing structure only includes validation for required fields, but I am looking to add additional validations such as minLength, email, and postcode. One challenge I face is cre ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

Vue encountered a double loading issue when utilizing a library compiled with Webpack

I am facing an issue with my TypeScript library of Vue components that gets compiled into a single JS file using Webpack. The problem arises when the TypeScript project consuming this library also depends on Vue. Upon running the application, I noticed tha ...

An undefined variable in Angular 2's evaluation

I am currently working with the following code: @ViewChild('MondayPicker') MondayPicker; @ViewChild('TuesdayPicker') TuesdayPicker; @ViewChild('WednesdayPicker') WednesdayPicker; @ViewChild('ThursdayPicker') Thursda ...

Is it possible to execute an HTTP request using a functional resolver?

Previously, I used a class-based resolver where I could inject HttpClient in the constructor. However, this approach has now been deprecated - see the source for more information. Now, I am looking to implement an HTTP get request in a functional resolver ...

Why does the page not work when I enter a certain URL with an ID parameter, and instead displays the error message "Uncaught ReferenceError: System is not defined"?

This is my "app.routing.ts": import {provideRouter, RouterConfig} from "@angular/router"; import {DashboardComponent} from "./dashboard.component"; import {HeroesComponent} from "./heroes.component"; import {HeroDetailsComponent} from "./hero-details.com ...

Having trouble getting TypeScript to install using npm on a Mac?

My goal is to use Typescript as a local dependency by checking it into my devDependencies and using it via an npm script after installing it with 'npm install'. However, when I try this on my machine, I find that Typescript (and webpack-cli as w ...

Send a Date Object through an Event Emitter to be used in a Date Picker

I created a personalized Date Picker Child Component, and when the onDateChange event occurs, I intend to send an event to the parent component. @Output() selectedDateChange = new EventEmitter<Date>(); onDateChange($event) { this.selectedDateCha ...

Broken Encoding Issue with Server-Side HttpClient Response in Angular 5 Universal

I have encountered an issue with Angular 5 Universal and server side rendering (ssr). When I make a GET request using HttpClient on the server side, the response seems to have encoding problems. However, the same code works perfectly fine on the client sid ...

substitute one item with a different item

I am facing an issue with updating the address object within an organization object. I receive values from a form that I want to use to update the address object. However, when I try to change the address object in the organization using Object.assign, i ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

An issue has been identified with the functionality of the router-out

Issue with Router Loading Component Outside of the router-outlet in app.component.ts @Component({ selector : "body", template : `<router-outlet></router-outlet>`, directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: "/aut ...