我的組件源函數中使用的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