我目前正在将Angular 2与Electron一起使用(基本上是使用Node和Web技术来创建GUI)。
我要做的就是列出当前目录的文件。
不幸的是,变量“ 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
}
}
Run Code Online (Sandbox Code Playgroud)
这可能是由引起的fs.readdir。似乎它使用的不是Angulars区域修补的API。要变通,您可以使用
export class FilesComponent {
constructor(private cdRef:ChangeDetectorRef) {}
loadFiles() {
fs.readdir(this.cwd, (err, dir) => {
for (let filePath of dir) {
console.log(filePath);
this.files.push(filePath);
}
this.cdRef.detectChanges();
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1293 次 |
| 最近记录: |