【问题标题】:'this' bound to subscribe function and not outer component scope in Angular2'this' 绑定到订阅函数而不是 Angular2 中的外部组件范围
【发布时间】:2020-05-18 04:19:07
【问题描述】:

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

组件:

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;
            },
            () => {

            },
            () => {

            }
        )
    }
}

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

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

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

谢谢

【问题讨论】:

    标签: javascript angular typescript this


    【解决方案1】:

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

    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()
         }
    

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      相关资源
      最近更新 更多