diff --git a/app/angular/src/client/preview/angular/helpers.ts b/app/angular/src/client/preview/angular/helpers.ts index fa39fdcc542..e554b84435b 100644 --- a/app/angular/src/client/preview/angular/helpers.ts +++ b/app/angular/src/client/preview/angular/helpers.ts @@ -1,10 +1,10 @@ // @ts-ignore import { document } from 'global'; -import { enableProdMode, NgModule, Component, NgModuleRef, Type } from '@angular/core'; +import { enableProdMode, NgModule, Component, NgModuleRef, Type, NgZone } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { BrowserModule } from '@angular/platform-browser'; -import { ReplaySubject } from 'rxjs'; +import { Observable, ReplaySubject, Subscriber } from 'rxjs'; import { StoryFn } from '@storybook/addons'; import { AppComponent } from './components/app.component'; import { STORY } from './app.token'; @@ -18,13 +18,27 @@ declare global { let platform: any = null; let promises: Promise>[] = []; -let storyData = new ReplaySubject(1); +let storyData = new ReplaySubject(1); const moduleClass = class DynamicModule {}; const componentClass = class DynamicComponent {}; type DynamicComponentType = typeof componentClass; +function storyDataFactory(data: Observable) { + return (ngZone: NgZone) => new Observable((subscriber: Subscriber) => { + const sub = data.subscribe( + (v: T) => { ngZone.run(() => subscriber.next(v)); }, + (err) => { ngZone.run(() => subscriber.error(err)); }, + () => { ngZone.run(() => subscriber.complete()); } + ); + + return () => { + sub.unsubscribe(); + }; + }); +}; + const getModule = ( declarations: (Type | any[])[], entryComponents: (Type | any[])[], @@ -34,13 +48,16 @@ const getModule = ( ) => { // Complete last ReplaySubject and create a new one for the current module storyData.complete(); - storyData = new ReplaySubject(1); + storyData = new ReplaySubject(1); storyData.next(data); const moduleMeta = { declarations: [...declarations, ...(moduleMetadata.declarations || [])], imports: [BrowserModule, FormsModule, ...(moduleMetadata.imports || [])], - providers: [{ provide: STORY, useValue: storyData }, ...(moduleMetadata.providers || [])], + providers: [ + { provide: STORY, useFactory: storyDataFactory(storyData.asObservable()), deps: [ NgZone ] }, + ...(moduleMetadata.providers || []) + ], entryComponents: [...entryComponents, ...(moduleMetadata.entryComponents || [])], schemas: [...(moduleMetadata.schemas || [])], bootstrap: [...bootstrap],