2016-06-30 44 views
2

我目前正在使用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 
    } 
} 
+0

'showFiles()'做什麼? –

+0

在代碼中幾乎沒有任何內容。但由於某種原因,UI單擊時會顯示所有文件。 –

+2

關於爲什麼它在你點擊時工作:點擊事件是由Angular的zone修補的,所以你的模板數據綁定在點擊事件處理程序運行後被檢查。由於自上次檢查後'文件'已更改,視圖將更新。我不知道Electron是如何工作的,但正如@Günter已經回答的那樣,Node.js中的異步事件可能不是猴子修補的,所以當'readdir'回調運行時,角度變化檢測不會被觸發。 –

回答

4

這可能是由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(); 
    }); 
    } 
} 
+0

你能詳細解釋一下嗎?我從來沒有見過'ChangeDetectorRef'。鏈接將有所幫助。但是這已經解決了這個問題。非常感謝! –

+2

@YahyaUddin,https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html#!#detectChanges-anchor。 –