在Node中对变量/模型进行更改时,Angular 2不会更新UI [英] Angular 2 is not updating the UI when making changes to a variable/model in Node

查看:72
本文介绍了在Node中对变量/模型进行更改时,Angular 2不会更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将Angular 2与Electron一起使用(基本上是使用Node和Web技术来创建GUI).

I am currently using Angular 2 with Electron (which is basically using Node and web technologies to create a GUI).

我要做的就是列出当前目录中的文件.

All I want to do is list the files of the current directory.

不幸的是,变量"this.files"似乎没有更新UI上显示的数据.但是,令人惊讶的是,当我单击链接到空方法的虚拟按钮时,它突然更新.我该如何解决此问题以及出了什么问题?

Unfortunately, the variable "this.files" does not seem to update the data shown on the UI. Surprisingly however, when I click the dummy button thats linked to an empty method, it suddenly update. How do I fix this issue and whats the problem?

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
    }
}

推荐答案

这可能是由fs.readdir引起的.似乎它使用的不是Angulars区域修补的API.要变通,您可以使用

That's probably caused by fs.readdir. It seems it is using an API that is not patched by Angulars zone. To work around you can use

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();
     });
   }
}

这篇关于在Node中对变量/模型进行更改时,Angular 2不会更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆