Angular 防止服务注入到另一个服务

Angular 防止服务注入到另一个服务,angular,Angular,我使用库来显示通知。此库包含ToastrService。但是,我想为这个服务创建我自己的包装器,因为我需要为不同类型的消息进行不同的配置。因此,我: @Injectable() export class NotificationService { constructor(private toastrService: ToastrService) { } public success(message: string, title?: string): void { this.

我使用库来显示通知。此库包含
ToastrService
。但是,我想为这个服务创建我自己的包装器,因为我需要为不同类型的消息进行不同的配置。因此,我:

@Injectable()
export class NotificationService {
  constructor(private toastrService: ToastrService) {
  }

  public success(message: string, title?: string): void {
    this.toastrService.success(message, title);
  }

  public error(message: string, title?: string): void {
    let toastConfig = {
      ...
    };
    this.toastrService.error(message, title, toastConfig);
  }

  public info(message: string, title?: string): void {
    let toastConfig = {
      ...
    };
    this.toastrService.info(message, title, toastConfig);
  }

  public warning(message: string, title?: string): void {
    this.toastrService.warning(message, title);
  }
}
我想阻止其他开发人员在某个地方注入strservice。如果用户向组件或除
NotificationService
之外的其他服务注入了strservice,我想抛出错误。我该怎么做

模块:

@NgModule({
  imports: [
    ToastrModule.forRoot(),
  ],
  declarations: [],
  providers: [    
    NotificationService
  ],
  exports: []
})
如果用户向组件或除 NotificationService我想抛出错误

你不需要那样做。让他们都通过通常的令牌
来消费服务,但他们将获得您的装饰
通知服务的实例

此库在模块级别上声明
ToastrService
。您可以使用相同的令牌在根组件级别重新定义此服务:

@Component({
   providers: [
      { provide: ToastrService, useClass: NotificationService} 
})
export class AppRootComponent {}
当根应用程序组件的子组件请求该服务时,它将获得该服务的修饰版本

如果您仍然想抛出错误(尽管我相信装饰不是这样做的),您可以这样做:

class ToastrServiceThatThrows { 
    constructor() { throw new Error('I should not be instantiated') } 
}

@Component({
   providers: [
      { NotificationService  },
      { provide: ToastrService, useClass: ToastrServiceThatThrows }  
})
export class AppRootComponent {}
但是您必须在
通知服务上使用
@SkipSelf()

@Injectable()
export class NotificationService {
  constructor(@SkipSelf() private toastrService: ToastrService) {  }

这样您就可以从模块注入器中获得真正的类实例。不要在模块上注册
NotificationService
,只在根组件上注册。

如何将其添加到应用程序中?我更新了问题,我添加了模块定义,如果我理解正确的话。这不是我真正想要的。一个开发人员可以注入到strservice,另一个开发人员可以注入NotificationService。。。。是的,在这两种情况下都将注入NotificationService。。。。但在代码中,它看起来像两个不同的服务。这就是为什么我想显式抛出错误,当开发人员使用ToastServiceNow时,我得到异常
没有ToastServiceProvider你能根据我的建议设置一个最小的plunker吗?我来看看好的,确保你没有在模块上注册
NotificationService
,只在根组件上注册如果我从模块中删除
NotificationService
,那么
没有NotificationService的提供者