问题:当我尝试在addEventListener中调用服务时,服务似乎是空的。
HTML:
<div id="_file0">
服务:
@Injectable()
export class FilesService {
constructor(private http : Http) { }
}
组件:
export class NoteComponent implements OnInit {
constructor(private filesService : FilesService) { }
ngOnInit() {
this.addEvent(document.getElementById("_file0"));
}
addEvent(div){
console.log("tag1", this.filesService);
div.addEventListener("click", function(){
console.log("tag2", this.filesService);
});
}
}
控制台输出:
tag1 FilesService {http: Http}
tag2 undefined
答案 0 :(得分:3)
尝试使用此代码维护this
上下文
div.addEventListener("click", () => {
console.log("tag2", this.filesService);
});
附加信息:这称为箭头功能或lamda功能。它实际上做的是当Typescript将你的代码编译成javascript时,它会创建另一个_this
变量来存储真实的this
,每当你调用this
时,它都会被_this
替换。
这就是原始代码被编译的原因,this
是undefined
,因为click
事件的上下文不是你的Angular组件。