【问题标题】:Angular Elements - multiple instances share the same service by defaultAngular Elements - 多个实例默认共享同一个服务
【发布时间】:2021-07-02 14:51:06
【问题描述】:

我已经基于角度元素创建了自己的 web 组件。我都是按照说明书做的。

示例代码为:

    const el = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('my-widget', el);

我也有 ApplicationService:

@Injectable({ providedIn: 'root' })
export class ApplicationService {}

毕竟,当我运行漂亮的“我的小部件”元素时 - 1 个实例运行良好。但是如果我运行两次,看起来 ApplicationService 总是只运行一次(单个实例)。

例子:

<my-widget id="widget1"></my-widget>
<my-widget id="widget2"></my-widget>

我想实现每个人都有自己的实例。 我正在寻找解决方案,我注意到配置有额外的字段,如:strategyFactory in createCustomElement

{ injector: Injector; strategyFactory?: NgElementStrategyFactory; }

我不知道如何使用它。你有什么想法吗?

【问题讨论】:

    标签: angular dependency-injection web-component angular-elements


    【解决方案1】:

    不要使用{ providedIn: 'root' },这会将服务注册为应用级别的单例。如果您需要为每个组件创建新实例,请使用组件的providers[]

    @Component({
      selector: 'my-widget',
      providers: [ApplicationService]
    })
    export class MyWidgetComponent
    

    【讨论】:

    • 我也试过了,但是在这个服务中我需要使用 HttpClient 并且我有在 App Module 中配置的 http 拦截器,并且正在使用该服务ApplicationService 在这种情况下,拦截器看不到一个。 ..当然这是好点,但还有更多的要求要满足
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多