gpt4 book ai didi

javascript - 'this' 绑定(bind)到订阅函数而不是 Angular2 中的外部组件范围

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:00 24 4
gpt4 key购买 nike

我在 Angular2 中的一个组件中遇到问题,因为“this”在我的一个组件中绑定(bind)到错误的上下文。我有其他组件没有发生此问题,但我看不出有什么区别。这是我的代码:

组件:

import { Component, Input } from '@angular/core';
import { FilesService } from "./services/files.service";

@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl:'/app/views/app.html'
})

export class AppComponent {
openFileUploader: boolean = false;
fileUploaderScope:any;

constructor (
private _filesService: FilesService
) {
let self = this;
_filesService.emitter.subscribe(
(response) => {
this.fileUploaderScope = response.filters;
this.openFileUploader = response.open;
},
() => {

},
() => {

}
)
}
}

在我的构造函数中,您可以看到我正在依赖注入(inject) filesService,然后使用“订阅”函数在构造函数本身内订阅从该服务返回的事件发射器。正如您从以下行中看到的那样,我正在监视事件,并在回调函数中将响应映射到一些局部组件变量:

_filesService.emitter.subscribe(
(response) => {
this.fileUploaderScope = response.filters;
this.openFileUploader = response.open;
},

这里唯一的问题是“this”没有绑定(bind)到正确的上下文。当我在该订阅函数中添加一个断点时,它说“this”未定义。我正在使用 Typescript(ECMA6 功能),所以箭头函数具有词法 this 绑定(bind)并在构造函数的上下文中定义,因此“this”应该绑定(bind)到组件?正如我所说,我还有其他具有相同功能的组件,它们在“this”上下文中没有问题,所以我很困惑为什么会这样。谁能发现我哪里出错了?

谢谢

最佳答案

我没有在您的代码中看到导致问题的模式,但通常是由

function () { ... }

代替

() => { ... }

或者像这样传递函数时

     _filesService.emitter.subscribe(
(response) => {
this.fileUploaderScope = response.filters;
this.openFileUploader = response.open;
},
errorHandler,
onCompleteHandler
}

代替

     _filesService.emitter.subscribe(
(response) => {
this.fileUploaderScope = response.filters;
this.openFileUploader = response.open;
},
errorHandler.bind(this),
onCompleteHandler.bind(this)
}

     _filesService.emitter.subscribe(
(response) => {
this.fileUploaderScope = response.filters;
this.openFileUploader = response.open;
},
(error) => errorHandler(error),
() => onCompleteHandler()
}

关于javascript - 'this' 绑定(bind)到订阅函数而不是 Angular2 中的外部组件范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40672869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com