问题
I have been trying to solve this problem for days: I'm doing an application that uses angular and electron, so I'm always in the production environment in angular. I use electron's ipcMain and ipcRender to communicate between the main process and the render to display csv files. The problem is that creating an observable fromEvent does not seem to trigger the angular changeDetection. Initially I solved the problem using ChangeDetectorRef but this creates strange behavior on the material components. To be sure not to make a mistake I copied the code from the tour of heroes application, if the observable is of ([1,2,3]) everything works... if I change the origin of the observable in fromEvent it doesn't work anymore.
the sercvice:
export class PresetService {
constructor(private electronService:ElectronService){}
read() {
this.electronService.ipcRenderer.send('read_presets');
}
getPresets():Observable<Preset[]> {
//return of([1,2,3,4]) //this works
this.read()
return fromEvent(this.electronService.ipcRenderer,'preset_res').pipe(
map(_=>_[1]),
tap(_ => console.log('fetched presets',_))//in the log i see an array of preset objects
);
}
}
the component
export class PresetsComponent implements OnInit {
public presets:any[] //already tried to use observable here and ngFor with async pipe and the behavior was the same
selected = new FormControl(0);
constructor(private presesetService:PresetService/*, private cdr: ChangeDetectorRef*/ ) {
}
ngOnInit() {
this.getPresets()
}
getPresets(): void {
this.presesetService.getPresets()
.subscribe(presets => {
this.presets = presets
//this.cdr.detectChanges() //if i add this i see all presets but material tabs do not works properly
});
}
addTab(selectAfterAdding: boolean) {
this.presets.push(new Preset());
if (selectAfterAdding) {
this.selected.setValue(this.presets.length - 1);
}
}
removeTab(index: number) {
this.presets.splice(index, 1);
}
}
and the template
<div>
<button mat-raised-button
class="example-add-tab-button"
(click)="addTab(selectAfterAdding.checked)">
Add new Preset
</button>
<mat-checkbox #selectAfterAdding> Select preset after adding </mat-checkbox>
</div>
<mat-tab-group [selectedIndex]="selected.value"
(selectedIndexChange)="selected.setValue($event)">
<mat-tab *ngFor="let preset of presets; let index = index" [label]="preset.ID">
Contents for {{preset.ID}}
<button mat-raised-button
class="example-delete-tab-button"
[disabled]="presets.length === 1"
(click)="removeTab(index)">
Delete Preset
</button>
</mat-tab>
</mat-tab-group>
回答1:
Issue solved wrapping the assignment in ngZone.run()
relevant code:
getPresets(): void {
this.presetService.getPresets()//wrap at this level do not solve the issue
.subscribe(presets => {
this.zone.run(()=>{
this.presets = presets //wrapping only this solve the issue
})
});
}
thanks frosty for the hint!
来源:https://stackoverflow.com/questions/58212459/observable-fromevent-do-not-activate-detectionchange-on-angular