Angular 在父到子组件中使用多个服务实例 [英] Angular Use Multiple Instances of Service In Parent to Child Components

查看:34
本文介绍了Angular 在父到子组件中使用多个服务实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父组件调用两个相同的子组件.子组件包含一个 SearchForm 和 Grid.

两个搜索网格以 iframe 格式并排显示.允许用户进行两次搜索.

在进行网格搜索时,他们似乎在使用相同的服务,并填充两个网格.在一个网格组件中进行搜索,在另一个组件中填充数据.正在克隆搜索.

如何确保每个子组件使用不同的服务实例?子组件在 html 选择器中调用.

<app-product-search-grid></app-product-search-grid><app-product-search-grid></app-product-search-grid>

不知道如何应用这个答案,使用同一服务的多个实例

子组件看起来像这样,

导出类 ProductSearchGridComponent构造函数(私有 productGridService:ProductGridService,

如果可能的话,我真的不想更改构造函数,因为它可能会影响其他人的代码.

解决方案

如果您需要在两个子项中单独的服务实例,您可以在组件级别提供您的服务:

@Component({/* ...*/提供者:[ProductGridService]})导出类 ProductSearchGridComponent {构造函数(私有服务:ProductGridService){}}

I have a Parent Component calling the two same Child components. The child component contains a SearchForm and Grid.

The two search grids are shown side by side, in iframe format. Allow users conduct two searches.

When doing a grid search, they seem to be utilizing the same service, and populating the two grids. Doing a search in one grid component, populates data in the other component. Searches are being cloned.

How do I make sure that each child component uses a different service instance? Child components are called in html selectors.

<div>
   <app-product-search-grid></app-product-search-grid>

   <app-product-search-grid></app-product-search-grid>
</div>

Not sure how to apply this answer, Using multiple instances of the same service

The child component looks as this,

export class ProductSearchGridComponent

  constructor(
    private productGridService: ProductGridService,

I really don't want to change the constructor if possible, as it may affect other people code.

解决方案

If you need a separate instance of the service in both children, you can provide your service at the component level:

@Component({
/* . . . */
  providers: [ProductGridService]
})
export class ProductSearchGridComponent {
  constructor(private service: ProductGridService) { }
 }

这篇关于Angular 在父到子组件中使用多个服务实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆