Angular2在回调中访问绑定实例变量
Angular2 accessing binding instance variable within callback
在 angular2 中我有以下组件:
import { Component } from '@angular/core';
const dialog = require("electron").dialog;
const xml2js = require('xml2js');
const fs = require("fs");
const ipc = require('electron').ipcRenderer;
@Component({
selector: 'ct-config-editor',
templateUrl: 'config.editor.component.html'
})
export class ConfigEditorComponent {
constructor() {
this.selected_file = 'Max';
}
clicked(event){
alert("lol");
ipc.send('open-file-dialog');
ipc.on('selected-directory', function (event, path) {
this.selected_file = `You selected: ${path}`;
});
}
}
视图有一个正确绑定的 属性 称为 selected_file,如下所示:
<h1>{{selected_file}}</h1>
H1 的值在开始时是最大的——但是在我的回调运行之后,我无法访问 this.selected_file
,因为 'this' 的上下文不是我的 class.
如何在回调中访问我的实例变量?
使用箭头函数保留上下文:
ipc.on('selected-directory', (event, path) => {
this.selected_file = `You selected: ${path}`;
});
这样 this
将引用您的 class
另请在此处查看更多详细信息
在 angular2 中我有以下组件:
import { Component } from '@angular/core';
const dialog = require("electron").dialog;
const xml2js = require('xml2js');
const fs = require("fs");
const ipc = require('electron').ipcRenderer;
@Component({
selector: 'ct-config-editor',
templateUrl: 'config.editor.component.html'
})
export class ConfigEditorComponent {
constructor() {
this.selected_file = 'Max';
}
clicked(event){
alert("lol");
ipc.send('open-file-dialog');
ipc.on('selected-directory', function (event, path) {
this.selected_file = `You selected: ${path}`;
});
}
}
视图有一个正确绑定的 属性 称为 selected_file,如下所示:
<h1>{{selected_file}}</h1>
H1 的值在开始时是最大的——但是在我的回调运行之后,我无法访问 this.selected_file
,因为 'this' 的上下文不是我的 class.
如何在回调中访问我的实例变量?
使用箭头函数保留上下文:
ipc.on('selected-directory', (event, path) => {
this.selected_file = `You selected: ${path}`;
});
这样 this
将引用您的 class
另请在此处查看更多详细信息