To view the code sample, visit the following link: stackblitz
In my data service, data is fetched asynchronously from a global object (in the actual project, data is emitted via EventEmitter).
The structure of the service is as follows:
import { Injectable } from '@angular/core';
import { Observable, Observer } from 'rxjs';
class DataEmitter {
public eventCallback: () => void;
constructor() {
setInterval(() => {
if (this.eventCallback) this.eventCallback();
}, 1000);
}
}
let emitter = new DataEmitter();
@Injectable({
providedIn: 'root',
})
export class DataService {
private counter = 1;
public dataSource = new Observable<number>((observer: Observer<number>) => {
emitter.eventCallback = () => {
observer.next(this.counter++);
};
});
constructor() {}
}
The respective Component subscribes to the observable for data display:
import { Component, VERSION, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
name = 'Angular ' + VERSION.major;
presentableData: number[] = [];
trigger = 0;
constructor(private dataService: DataService) {}
ngOnInit(): void {
this.dataService.dataSource.subscribe((num) => {
console.log('presentableData.length: ' + this.presentableData.length);
this.presentableData.push(num);
});
setInterval(() => this.trigger++, 10000);
}
}
Currently, the view does not update every second as expected. The global data emitting object seems to be outside the scope of the Observable subscribe method, resulting in the Component not re-rendering on data arrival. However, triggering it with another bound variable displays all the data.
Is this behavior normal or expected, or is it a bug within Angular?