Angular TypeScript this.X不是一个函数

Angular TypeScript this.X不是一个函数,angular,typescript,Angular,Typescript,我正在使用Angular 6构建一个应用程序。 在我的应用程序中,我有以下代码: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.c

我正在使用Angular 6构建一个应用程序。 在我的应用程序中,我有以下代码:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})

export class SearchComponent implements OnInit {

  constructor(private http: HttpClient) {}

  setBackgroundImage(){
    //code here..
  }

  searchCard(evt) {
    evt.preventDefault();

    let inputField_Id = <HTMLInputElement>document.getElementById("inputField_Id");
    let id = inputField_Id.value;
    //code here..

    if(id){
      let url = "http://localhost:3000/card/" + id;
      this.sendToServer(url);   //This is where the problem is
    }
  }

  sendToServer(url){
    this.http.get(url).subscribe(response => {
        //code here..
    });
  }

  ngOnInit() {
    this.setBackgroundImage();

    let searchForm = document.getElementById("searchForm");
    searchForm.addEventListener("submit", this.searchCard);
  }
}
从'@angular/core'导入{Component,OnInit};
从'@angular/common/http'导入{HttpClient};
@组成部分({
选择器:“应用程序搜索”,
templateUrl:'./search.component.html',
样式URL:['./search.component.css']
})
导出类SearchComponent实现OnInit{
构造函数(私有http:HttpClient){}
setBackgroundImage(){
//代码在这里。。
}
搜索卡(evt){
evt.preventDefault();
让inputField_Id=document.getElementById(“inputField_Id”);
设id=inputField\u id.value;
//代码在这里。。
如果(id){
让url=”http://localhost:3000/card/“+id;
this.sendToServer(url);//这就是问题所在
}
}
sendToServer(url){
this.http.get(url.subscribe)(响应=>{
//代码在这里。。
});
}
恩戈尼尼特(){
此.setBackgroundImage();
让searchForm=document.getElementById(“searchForm”);
searchForm.addEventListener(“提交”,此.searchCard);
}
}
我试图从函数
搜索卡
中调用方法/函数
sendToServer
,但我无法做到这一点。 它告诉我“this.sendToServer不是位于…的函数”

如果I
console.log(这个)
searchCard
中,我得到触发提交事件的HTMLform元素

如果我创建了一个
让self=this函数中的变量我得到相同的结果

相反,我尝试将self创建为类
SearchComponent
的属性,并设置
self=this
ngOnInit
功能中。但是self==窗口对象。我在构造函数中尝试了同样的方法,但结果相同

如何从searchCard中调用sendToServer?

试试这个

searchForm.addEventListener("submit", (event)=>{
 this.searchCard(event);
 });
它应该可以正常工作

它的工作原理是,箭头函数绑定上下文,知道下一个函数中的this与类中的this相同,我们可以使用它从类中调用函数


您可以阅读有关箭头函数和绑定的更多信息,因为箭头函数绑定上下文。虽然这段代码可以回答这个问题,提供有关如何和/或为什么解决问题的附加上下文将提高答案的长期价值。您可以在此处阅读有关箭头函数的更多信息。可能重复的可能重复