Angular 以编程方式将服务注入函数

Angular 以编程方式将服务注入函数,angular,dependency-injection,rxjs,Angular,Dependency Injection,Rxjs,我有一个自定义的RxJs函数,它可以处理http调用的异常,如下所示(简化) 然后,在同一app.component中,我在构造函数中注入了AngularInjector,并填充了全局变量,如下所示: export let GlobalAppInjector: Injector; @Component({ selector: 'skeleton-root', templateUrl: './app.component.html', styleUrls: ['./app.compon

我有一个自定义的RxJs函数,它可以处理http调用的异常,如下所示(简化)

然后,在同一app.component中,我在构造函数中注入了Angular
Injector
,并填充了全局变量,如下所示:

export let GlobalAppInjector: Injector;

@Component({
  selector: 'skeleton-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {

  constructor(private injector: Injector){
    GlobalAppInjector = this.injector;
  }
}
我选择此解决方案的原因是,我无法直接从自定义函数访问现有的喷油器。我不喜欢的是,我刚刚在app.component中创建了一个依赖项,这仅仅是为了我的自定义函数,这似乎是一种过度使用


我相信应该有更好的方法来做这件事。非常感谢您在这方面提供的任何帮助。

与其尝试在全球范围内注册
注入器,不如建议您将注入器作为RxJs操作员的参数


这是一种更干净的方法,并且可以进行单元测试。

如果您确实想污染您的全局范围,您可以将injector实例分配给
窗口
-对象,但我不推荐这样做。我试图完全避免使用全局变量,然而,将喷油器直接注入到服务中是我没有想到的好方法。非常感谢。
export let GlobalAppInjector: Injector;
export let GlobalAppInjector: Injector;

@Component({
  selector: 'skeleton-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {

  constructor(private injector: Injector){
    GlobalAppInjector = this.injector;
  }
}