在Node中对变量/模型进行更改时,Angular 2不会更新UI

Yah*_*din 3 node.js angular

我目前正在将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)

Gün*_*uer 5

这可能是由引起的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)

  • @YahyaUddin,https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html#!#detectChanges-anchor。 (2认同)