簡體   English   中英

如何在 angular 故事書組件中注入服務?

[英]How to inject services in angular storybook components?

Github: https://github.com/danielhdz56/storybook-demo.git

在組件中注入服務總是會在故事書中引發錯誤:

Error: Can't resolve all parameters for CustomService: (?).

一個示例組件:

 @Component({
   selector: 'app-custom-selector',
   templateUrl: './custom-selector.component.html',
   styleUrls: ['./custom-selector.component.scss'],
 })
 export class NavigationItemComponent {
   constructor(private customService: CustomService) {}
 }

喲需要將它們添加到模塊元數據中

const modules = {
    imports: [..],
    providers: [CustomService],
    declarations: [NavigationItemComponent ]
};

// Then in stories: 
.add('description',
    () => ({
        component: NavigationItemComponent ,
        props: {...},
        moduleMetadata: modules
    }
)

您能否分享您的自定義服務的代碼可能是您沒有將它注入可注入。@injectable 裝飾在您的服務之上

@angular/coreAPP_INITIALIZER的幫助下,當使用其他主機組件時,我通過為所需服務使用自定義工廠初始化程序解決了這個問題:

import { APP_INITIALIZER } from '@angular/core';

function myServiceFactory(myService: MyService) {
  return () => myService;
}

const meta: Meta<MyCustomComponent> = {
  title: 'Components/Custom component',
  component: MyCustomComponent,
  argTypes: {
  },
  decorators: [
    moduleMetadata({
      imports: [
        BrowserAnimationsModule,
        BrowserModule,
        CommonModule,
      ],
      providers: [
        provide: APP_INITIALIZER,
        useFactory: myServiceFactory,
        deps: [MyService],
      ]
    }),
  ],
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM