0
  • My Component Source

    import { Component, OnInit } from '@angular/core';
    import { Http } from '@angular/http';
    
    //import { DatatableComponent } from '../../shared/ui/datatable/datatable.component'
    
    @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 wonder...

I added the Click event to the addEventListener method.

The http used in the function is undefined. Why? I do not know the reason.

I have to use http inside the function. Is there a way?

  • 2
    use an arrow function instead, and have a read on **this** in javascript. – toskv Aug 03 '17 at 06:21
  • 7
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – AT82 Aug 03 '17 at 06:21
  • addEventListener is jQuery event so the http function is undefined inside the JQuery block. For button click event just do like this – Sreemat Aug 03 '17 at 06:23
  • By the way, should not you return response.json()? – Mohammad Kermani Aug 03 '17 at 07:13
  • I would also just use (click)="handler()" in template.. No need for JQuery like element lookup. Then put http inside handler.. Your method would also warrant an ngDestroy to removeEventListener otherwise you'd likely run into memory leaks.. – JGFMK Aug 03 '17 at 07:31

2 Answers2

0

your code

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

Should be

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

More

https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

basarat
  • 261,912
  • 58
  • 460
  • 511
0

This 'this' is not the 'this' you want. You can use arrow function instead or call bind(this) in the end.

 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")
        );

      }.bind(this)

In fact, you should implement that like :

@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")
        );

    }

}