javascript - Angular 2 中流的更改检测?

标签 javascript angular buffer angular2-changedetection

在组件中读取流时,我无法分配变量。

import { Component, OnInit } from '@angular/core';
var fs: any = require('fs');

 @Component({
 selector: 'stream-cmp',
 templateUrl: 'app/view/stream.html',
 styleUrls: ['./app/view/stream.css'],
 })


 export class StreamCmp {

 private _anotherVariable:any = null;
 private readstream:any = null;
 private filePath:any = '/dir/file';

 public fileUpload():void {



    this.readstream =  fs.createReadStream(this.filePath, {start: 140, end:  160});

    this.readstream.on('data', function (text) {

     console.log(text);
     this.filePath = text;

    });

 }

基本上, this.filePath 从未被分配,我从未在 View 中看到它。但 console.log 始终有效。

我是否使用某种类型的更改检测(可能是changedetectionref,因为与 NgZone 相比它应该更快)?既然它是一个流,我们是否可以一次性获取所有内容?它是异步流吗?我应该调用 fs 模块上的属性来将数据写入变量吗?看来 fs 模块上的管道函数是为了写入文件或其他流。

最佳答案

您应该使用arrow函数来访问函数内的当前上下文。仅更改此内容并不能解决您的问题。

目前,您在data(自定义)事件上使用了一些函数,用于从文件流接收数据。因此,在这种情况下,更改检测系统不会知道任何组件绑定(bind)中的某些内容发生了更改。这就是为什么在这种情况下您必须手动运行更改检测来更新页面上的绑定(bind)。您需要在组件构造函数中添加private ref: ChangeDetectorRef,这将使更改检测器引用对象可供您使用。接下来,您将调用 this.ref.detectChanges() 方法来手动运行区域以检查和更新页面上的绑定(bind)。

代码

this.readstream.on('data', (text) => { // changed here to use arrow function.
 console.log(text);
 this.filePath = text; //this.filePath will be the component variable which has been declared
   this.ref.detectChanges(); //will trigger change detection system manually.
}); 

Change Detection

Zone is core of change detection system, it monkey patches almost all the event internally like setTimeout, setInterval, DOM events, etc. and when you trigger them it atomically run change detector system to once those event get called. If you have any custom event which doesn't fits in this list that time you have to trigger Change Detection system manually to make all binding in sync.

还有其他几种手动运行更改检测的方法,您可以在 this answer 中找到它。作者:@Mark Rajcok

关于javascript - Angular 2 中流的更改检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488609/

相关文章:

javascript - 设置全局变量并在 jquery/javascript 中访问它

javascript - 即使元素被删除后也会多次触发事件监听器?

angular - 导出为的多个指令

angular - 如何使用 angular2 和 webpack 缩小 html 模板?

node.js - 如何在MongoDB中设置缓冲区偏移范围,它不允许在BSON对象中上传超过16MB的文件?

javascript - PassportJs Google Auth2 失败重定向不起作用

javascript - 如何在 react/javascript 中用自定义图像组件替换 <img>

angular - ngx-translate 不适用于延迟加载模块

c - memcpy正确的实现方式

c - sprintf 缓冲区大小