我可以在DOM addEventListener中使用Angular2服务吗?

时间:2017-03-14 20:04:31

标签: javascript angular events dom

问题:当我尝试在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

1 个答案:

答案 0 :(得分:3)

尝试使用此代码维护this上下文

div.addEventListener("click", () => {
    console.log("tag2", this.filesService);
});

附加信息:这称为箭头功能或lamda功能。它实际上做的是当Typescript将你的代码编译成javascript时,它会创建另一个_this变量来存储真实的this,每当你调用this时,它都会被_this替换。

这就是原始代码被编译的原因,thisundefined,因为click事件的上下文不是你的Angular组件。

相关问题