You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular Storybook中注入真实服务并调用其方法

在Angular Storybook中注入真实服务的解决方案

原代码的核心问题是模板无法直接访问Injector实例,导致点击事件中传递的injector为undefined,无法获取到NotificationService。以下是可行的解决方式:

方法一:通过moduleMetadata注入服务并使用inject函数获取实例

在Storybook配置中添加moduleMetadata装饰器,将真实服务注册到providers中,然后在事件处理函数里用Angular的inject函数直接获取服务实例:

import { moduleMetadata, inject } from '@storybook/angular';
import { NotificationService } from 'path/to/your/notification.service';

export default {
  title: 'Button/NotificationDemo',
  // 配置Storybook模块元数据,注入真实服务
  decorators: [
    moduleMetadata({
      providers: [NotificationService]
    })
  ]
};

export const ShowNotification = () => ({
  props: {
    uType: 'secondary',
    withDelay: () => {
      // 直接获取已注入的真实服务实例
      const notificationService = inject(NotificationService);
      notificationService.show("Hello from Storybook!");
      alert("hello");
    }
  },
  template: `<button uAction [uType]="uType" (click)="withDelay()">Show notification</button>`
});

方法二:手动创建Injector获取服务实例

如果不想依赖moduleMetadata,也可以在事件处理函数中手动创建Injector并注入真实服务:

import { Injector } from '@angular/core';
import { NotificationService } from 'path/to/your/notification.service';

export default {
  title: 'Button/NotificationDemo'
};

export const ShowNotification = () => ({
  props: {
    uType: 'secondary',
    withDelay: () => {
      // 创建Injector并注册真实服务
      const injector = Injector.create({
        providers: [{ provide: NotificationService, useClass: NotificationService }]
      });
      const notificationService = injector.get(NotificationService);
      notificationService.show("Hello from Storybook!");
      alert("hello");
    }
  },
  template: `<button uAction [uType]="uType" (click)="withDelay()">Show notification</button>`
});

关键说明

  • 方法一更符合Angular的依赖注入规范,推荐使用。通过moduleMetadata注册的服务会在整个Storybook组件树中可用,无需重复创建Injector。
  • 方法二适合临时测试场景,但每次调用都会创建新的服务实例,可能不符合实际业务逻辑。

内容的提问来源于stack exchange,提问作者Aravintha Bashyam.c

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:09:57