繁体   English   中英

从函数 angular2 调用服务

[英]Calling service from a function angular2

我正在尝试从函数调用服务,但在控制台中出现此错误:

无法读取未定义的属性“TestMethod”

这是我的代码:

  • app.component.ts:

     constructor(public _service: BackendFileCodeService){ } public editor; EditorCreated(quill) { const toolbar = quill.getModule('toolbar'); this.editor = quill; // console.log(quill) toolbar.addHandler('image', this.imageHandler); } imageHandler(value) { // document.querySelector('input.ql-image[type=file]').addEventListener('click', () => { // console.log('Hello'); // }); const ImageInput = document.createElement('input'); ImageInput.setAttribute('type', 'file'); ImageInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon'); ImageInput.classList.add('ql-image'); ImageInput.click(); ImageInput.addEventListener('change', () => { const file = ImageInput.files[0]; if (ImageInput.files != null && ImageInput.files[0] != null) { this._service.TestMethod('Hello'); } }); }
  • 后端文件代码服务:

     import { Injectable } from '@angular/core'; @Injectable() export class BackendFileCodeService { constructor() { } TestMethod(test){ return test; } }

我正在尝试在名为 imageHandler 的函数内调用服务,特别是在

ImageInput.addEventListener

但是我提到了错误,我尝试从 imageHandler 函数外部调用该服务,并且每个都按预期工作。

注意:该服务是控制台日志“hello”作为测试。

对 imageHandler 函数使用粗箭头语法应该可以解决这个问题。

imageHandler(value) {...}
...
imageHandler = (value) => { ... }

如果不能使用粗箭头语法,则需要创建一个变量来捕获组件范围,最常见的方法是声明一个变量并分配给它,

self = this;
imageHandler(value) {
 ....
 self._service.TestMethod('Hello');
 ....
}

我看到您已经在使用下面的粗箭头语法,这很好,否则您还需要捕获imageHandler范围。

ImageInput.addEventListener('change', () => {

在此处阅读有关打字稿中函数作用域的更多信息,

this箭头函数

在 JavaScript 中,这是一个在调用函数时设置的变量。 这使它成为一个非常强大和灵活的特性,但它的代价是始终必须知道函数正在执行的上下文。这是众所周知的混乱,尤其是在返回函数或将函数作为参数传递时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM