我有一个使用 Angular Bootstrap 的 Toast 组件:
@Component({
selector: 'app-toast',
template: `
<ngb-toast
*ngFor="let toast of toastService.toasts"
[header]="toast.headertext"
[class]="toast.classname"
[autohide]="toast.autohide"
[delay]="toast.delay || 5000"
(hide)="toastService.remove(toast)"
>
<ng-template [ngIf]="isTemplate(toast)" [ngIfElse]="text">
<ng-template [ngTemplateOutlet]="toast.textOrTpl"></ng-template>
</ng-template>
<ng-template #text>{{ toast.textOrTpl }}</ng-template>
</ngb-toast>
`,
})
export class ToastComponent {
@HostBinding('class.ngb-toasts') toastClass = true;
constructor(public toastService: ToastService) {}
isTemplate(toast: any) {
return toast.textOrTpl instanceof TemplateRef;
}
}
此组件模板通过服务调用:
export class ToastService {
toasts: any[] = [];
show(textOrTpl: string | TemplateRef<any>, options: any = {}) {
this.toasts.push({ textOrTpl, ...options });
}
}
<app-toast></app-toast>
因此,从任何具有.
this.toastService.show('Some message', {
classname: 'bg-success text-light',
delay: 2000,
autohide: true,
});
问题:如何定义使用 Service 来呈现组件的故事?show
如您所见,除非通过该方法 调用服务,否则组件不会呈现模板。我怎样才能在故事中复制这一点?
到目前为止的故事:
import { moduleMetadata } from '@storybook/angular';
import { Story, Meta } from '@storybook/angular/types-6-0';
import { ToastComponent } from './toast.component';
import { CommonModule } from '@angular/common';
import { ToastService } from './toast.service';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
export default {
title: 'Toast',
component: ToastComponent,
decorators: [
moduleMetadata({
providers: [ToastService],
imports: [CommonModule, NgbModule],
}),
],
} as Meta;
const Template: Story<ToastComponent> = (args: ToastComponent) => ({
component: ToastComponent,
props: args,
});
export const Primary = Template.bind({});
试过:
我试过new
在故事中实例化一个服务,但这不起作用。
我也可以demo
为故事书创建一个组件,它自己从服务中调用show
方法,但我宁愿不必为故事书和任何其他组件创建额外的组件,而是按原样使用,因为它更容易管理.
有没有办法在故事书中调用服务并调用show
里面的函数?