2
我在Angular2中的一個組件中遇到問題,因爲'this'在我的組件之一中綁定了錯誤的上下文。我有其他組件,這個問題沒有發生,但我看不出有什麼不同。這裏是我的代碼:'this'在Angular2中綁定訂閱函數而不是外部組件範圍
組件:
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;
},
這裏唯一的問題是,「這個」不綁定:你可以從以下幾行,我再留意事件,並在回調函數,我映射到某些局部組件變量的響應見正確的上下文。當我在該訂閱功能中添加斷點時,它說「這個」沒有定義。我正在使用Typescript(ECMA6功能),所以箭頭函數具有詞法綁定,並在構造函數的上下文中定義,因此'this'應該綁定到組件? 正如我所說我有其他組件具有相同的功能,這與'這個'上下文沒有問題,所以我很困惑,爲什麼會發生這種情況。任何人都可以發現我出錯的地方嗎?
感謝