簡體   English   中英

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”的上下文不是我的課程。

如何在回調中訪問我的實例變量?

使用箭頭功能保留上下文:

ipc.on('selected-directory', (event, path) => {
   this.selected_file = `You selected: ${path}`;
});

這樣, this將被引用給您的班級

在這里查看更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM