一个组件具有两个相同服务的实例

时间:2020-08-24 15:38:07

标签: javascript angular typescript

我有一个查询生成器服务,我想在一个组件中使用两次。能做到吗?我已经尝试过两次注入服务,但这似乎不起作用,因为服务只是互相引用,如下所示:

With

我不确定这是否是由于设置了我的提供程序(又称为多选项)而引起的,但它看起来像这样:

@Component({
  selector: 'app-manage-users',
  templateUrl: './manage-users.component.html',
  styleUrls: ['./manage-users.component.scss'],
  providers: [UserManagementQueryBuilderProvider]
})
export class ManageUsersComponent implements OnInit {

  public constructor(
    private readonly queryBuilder: QueryBuilderService,
    private readonly qb: QueryBuilderService
  ) { }

  public ngOnInit() {
    this.queryBuilder.table('users');
    console.log(this.qb['_table']); // Outputs "users"; expecting an empty string.
  }
}

如果将export const UserManagementQueryBuilderProvider: Provider = { useFactory: (httpClient: HttpClient) => new QueryBuilderService(httpClient) .connection(environment.USER_MANAGEMENT_API), provide: QueryBuilderService, deps: [HttpClient], multi: false }; 设置为multi,则会收到一条错误消息,指出该表不是函数。

错误错误:未捕获(承诺):TypeError:this.queryBuilder.table不是函数

true如下所示:

QueryBuilderService

1 个答案:

答案 0 :(得分:3)

别名提供商
使用useExisting提供程序密钥,可以将一个令牌映射到另一个令牌。实际上,第一个令牌是与第二个令牌关联的服务的别名,从而创建了两种访问同一服务对象的方式。 (Angular Docs

考虑提供两个InjectionToken并将UseExisting设置为false的{​​{1}},这样将注入QueryBuilderService的两个不同实例,如下所示:

import { Component, InjectionToken, Inject } from '@angular/core';

const QueryBuilder1 = new InjectionToken("QB1")
const QueryBuilder2 = new InjectionToken("QB2")

@Component({
  providers: [
    {
      provide: QueryBuilder1,
      useClass: QueryBuilderService,
      useExisting: false
    },
    {
      provide: QueryBuilder2,
      useClass: QueryBuilderService,
      useExisting: false
    }
  ]
})
export class ManageUsersComponent {

  public constructor(
    @Inject(QueryBuilder1) private queryBuilder1: QueryBuilderService,
    @Inject(QueryBuilder2) private queryBuilder2: QueryBuilderService
  ) { }

}