0

I am not able to assign a variable while a stream is being read in a component.

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;

    });

 }

Basically, this.filePath is never assigned, I never see it in the view. But console.log always works.

Do I use change detection of some sort (maybe changedetectionref since it is supposed to be fast compared to NgZone)? Since it is a stream are we getting all of it at once? Is it an asynchronous stream? Is there a property on the fs module I should call to write the data to a variable? It seems the pipe function on the fs module is meant to write to files or other streams.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299

1 Answers1

2

You should be using arrow function to access current context inside function. Only changing this will not resolve your issue.

Currently you're hooked some function on data(custom) event for receiving a data from file stream. So in that case change detection system wouldn't come to know that the something got changed in any of component binding. That's why in this case you have to run change detection manually to update bindings over the page. You need to add private ref: ChangeDetectorRef in your component constructor which will make change detector reference object available to you. Next you will call this.ref.detectChanges() method to manually run zone to check & update bindings over a page.

Code

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.

There is couple of other way to run change detection manually, you can find it in this answer by @Mark Rajcok

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299