呼叫服务
问题描述:
我试图从一个函数调用一个服务,但我在控制台收到此错误:呼叫服务
无法读取的未定义的属性“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'); } }); }
-
BackendFileCodeService:
import { Injectable } from '@angular/core'; @Injectable() export class BackendFileCodeService { constructor() { } TestMethod(test){ return test; } }
我想打电话叫imageHandler函数内部的服务特别是在
ImageInput.addEventListener
但我在提到错误时,我试图从imageH外部调用服务安德勒功能和每一个这样的预期工作。
注意:该服务是控制台日志“hello”作为测试。
答
对你的imageHandler函数使用胖箭头语法应该可以解决这个问题。
imageHandler(value) {...}
...
imageHandler = (value) => { ... }
如果您不能使用胖箭头语法,你需要创建一个变量来捕获组件范围,最常见的方式是声明变量并分配到这一点,
self = this;
imageHandler(value) {
....
self._service.TestMethod('Hello');
....
}
我看到你已经在使用下面的胖箭头语法,这很好,否则你还需要捕获imageHandler
的范围。
ImageInput.addEventListener('change',() => {
了解更多关于function scopes in typescript here,
这和箭头功能
在JavaScript中,这是当一个函数是 称那我们设置一个变量。这使得它成为一个非常强大和灵活的功能,但它的代价是始终必须知道函数正在执行的上下文。这是非常令人困惑的,尤其是在返回函数或传递函数时出现的 论据。
希望这有助于!