我目前正在使用Angular 2與Electron(基本上使用Node和Web技術來創建GUI)。Angular 2在更改Node中的變量/模型時沒有更新UI
我想要做的就是列出當前目錄的文件。
不幸的是,變量「this.files」似乎沒有更新UI上顯示的數據。然而,令人驚訝的是,當我點擊鏈接到空方法的虛擬按鈕時,它突然更新。我如何解決這個問題以及最新的問題?
import {Component} from "@angular/core";
const fs = require('fs');
@Component(<any>{
selector: 'files',
template: `
<h2>Files</h2>
<ul *ngFor="let file of files">
<li>{{ file }}</li>
</ul>
<button (click)="showFiles">Show Files</button>
`,
})
export class FilesComponent {
files: any[];
cwd: string;
constructor() {}
ngOnInit() {
this.cwd = __dirname;
this.files = [];
this.loadFiles();
}
loadFiles() {
fs.readdir(this.cwd, (err, dir) => {
for (let filePath of dir) {
console.log(filePath);
this.files.push(filePath);
}
});
}
showFiles() {
// Empty method
// Shows the files for some reason despite nothing happening
}
}
'showFiles()'做什麼? –
在代碼中幾乎沒有任何內容。但由於某種原因,UI單擊時會顯示所有文件。 –
關於爲什麼它在你點擊時工作:點擊事件是由Angular的zone修補的,所以你的模板數據綁定在點擊事件處理程序運行後被檢查。由於自上次檢查後'文件'已更改,視圖將更新。我不知道Electron是如何工作的,但正如@Günter已經回答的那樣,Node.js中的異步事件可能不是猴子修補的,所以當'readdir'回調運行時,角度變化檢測不會被觸發。 –