我的组件源函数中使用的http是未定义的。为什么?
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 } }
我不知道......
我加入了Click事件addEventListener方法。
函数中使用的http是未定义的。为什么? 我不知道原因。
我必须在函数内部使用http。 有没有办法?
使用箭头函数来代替,并有阅读**这**在JavaScript。 – toskv
[如何在回调中访问正确的\'this \'](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) ) – Alex
addEventListener是jQuery事件,所以http函数在JQuery块内部是未定义的。对于按钮点击事件就像这样<按钮(点击)=“functionName()”>点击 – Sreemat