Sam*_*era 5 ngrx angular storybook angular-storybook
我有一个具有组件级提供程序的 Angular 组件。
@Component({
selector: 'storybook-di-component',
templateUrl: './di.component.html',
providers: [{ provide: TEST_TOKEN, useValue: 123 }],
})
export class DiComponent {
@Input()
title: string;
constructor(
protected injector: Injector,
protected elRef: ElementRef,
@Inject(TEST_TOKEN) protected testToken: number
) {}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我如何让故事书注入不同的提供者,以便我可以提供替代/模拟服务?例如,在上面的 DiComponent 中,如果我想改为注入{ provide: TEST_TOKEN, useValue: 456 }怎么办?
真实世界的用例是我正在使用 ngrx/component-store 并且需要为组件提供一个虚拟的、预填充的存储。
(附加信息:)在模块级别(如下所示)注入它不起作用,因为组件仍然会创建它自己的提供者实例:
moduleMetadata: {
providers: [
{ provide: StateStore, useValue: stateStore }
],
imports: [...],
},
Run Code Online (Sandbox Code Playgroud)
我最终使用低技术方法解决了这个问题。
.stories.ts对文件中的组件进行子类化super(...)使用注入的服务+模拟的服务进行调用。ngrx/component-store鉴于我的实际需要是注入我的模拟,stories.ts现在有类似以下内容:
const stateStore = new RecordSuggestionsPageStore(mockSuggestionsService);
stateStore.setState(() => ({
selectableRecords: [
{ name: "John Legend", recordType: "employee" },
{ name: "Allan Davies", recordType: "employee" },
]
}));
@Component({
selector: "myapp-suggested-records-page",
templateUrl: "./suggested-records-page.component.html",
styleUrls: ["./suggested-records-page.component.scss"]
})
class SuggestedRecordsPageComponentStubbed extends SuggestedRecordsPageComponent {
constructor(router: Router) {
super(stateStore, router);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1309 次 |
| 最近记录: |