我有一个具有组件级提供程序的 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
) {}
在这种情况下,我如何让故事书注入(inject)不同的提供者,以便我可以提供替代/模拟服务?例如,在上面的 DiComponent 中,如果我想注入(inject) { provide: TEST_TOKEN, useValue: 456 }
怎么办?真实世界的用例是我正在使用 ngrx/component-store 并且需要为组件提供一个虚拟的、预填充的存储。
(附加信息:)
在模块级别(如下所示)注入(inject)它不起作用,因为组件仍在运行并创建它自己的提供者实例:
moduleMetadata: {
providers: [
{ provide: StateStore, useValue: stateStore }
],
imports: [...],
},
最佳答案
我最终使用低技术方法解决了这个问题。
.stories.ts
中的组件文件 super(...)
注入(inject)服务+模拟服务。 鉴于我的实际需要是注入(inject)
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);
}
}
关于angular - 故事书:在组件级别注入(inject)一个模拟的提供者/服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64779479/