2017-07-28 140 views
1

我使用ngx-toastr库显示通知。此库包含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); 
    } 
} 

我想阻止其他开发人员在某处注入ToastrService。如果用户注入ToastrService到除NotificationService以外的组件或其他服务,我想抛出错误。我怎样才能做到这一点?

模块:

@NgModule({ 
    imports: [ 
    ToastrModule.forRoot(), 
    ], 
    declarations: [], 
    providers: [  
    NotificationService 
    ], 
    exports: [] 
}) 
+0

如何将它添加到您的应用程序? –

+0

我更新了问题,如果我正确理解了你的话,我已经添加了模块定义。 – user348173

回答

1

如果用户注入ToastrService到组件或其他服务,除了 NotificationService我想抛出的错误。

你不需要那样做。让他们都按照常规标记ToastrService使用服务,但他们将获得装饰的实例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()装饰上NotificationService

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

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

+0

这不是我真正想要的。一个开发人员可以注入ToastrService,另一个开发人员可以使用NotificationService ....是的,NotificationService将在这两种情况下注入....但在代码中它看起来像两个不同的服务。这就是为什么我想显式抛出错误的原因,当开发人员使用ToastrService – user348173

+0

@ user348173,更新了答案 –

+0

现在,我得到异常'''没有提供ToastrService!''' – user348173