Angular4:如何手动创建服务实例而不是在构造函数

时间:2017-11-13 07:00:36

标签: angular dependency-injection webpack angular-cli

我正在使用angular4。以下是 package.json

中的依赖项列表
"@angular/animations": "^4.0.0",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",

我正在拦截http请求,因此我扩展了Http类。现在我需要在提供程序中添加entery,所以在 app.module.ts

providers: [{
  provide: HttpInterceptor,
  useFactory: httpInterceptor,
  deps: [XHRBackend, RequestOptions]
}],

httpInterceptor是导出的函数

// to return an instance of HttpInterceptor class
export function httpInterceptor(backend: XHRBackend, defaultOptions: RequestOptions) {
    return new HttpInterceptor(backend, defaultOptions);
}

现在这是HttpInterceptor class

的构造函数
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
     super(backend, defaultOptions);
     this.router = ServiceLocator.injector.get(Router);
}

我无法直接在构造函数中注入Router服务,因此我已按照this answer手动注入服务。但这显示this.router未定义。当我调试它时,它显示ServiceLocator.injector

{
   message:"__WEBPACK_IMPORTED_MODULE_5__common_services_locator_service__ is not defined"
   stack : "ReferenceError: __WEBPACK_IMPORTED_MODULE_5__common_services_locator_service__ is not defined
    at eval (eval at webpackJsonp.../../../../../src/app/interceptors/http-interceptor.ts.HttpInterceptor.onCatch (http://localhost:7000/main.bundle.js:568:13), <anonymous>:1:1)
    at CatchSubscriber.webpackJsonp.../../../../../src/app/interceptors/http-interceptor.ts.HttpInterceptor.onCatch [as selector] (http://localhost:7000/main.bundle.js:568:13)
    at CatchSubscriber.webpackJsonp.../../../../rxjs/operators/catchError.js.CatchSubscriber.error (http://localhost:7000/vendor.bundle.js:18245:31)
    at XMLHttpRequest.onLoad (http://localhost:7000/vendor.bundle.js:84658:34)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:7000/polyfills.bundle.js:2970:31)
    at Object.onInvokeTask (http://localhost:7000/vendor.bundle.js:66251:33)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:7000/polyfills.bundle.js:2969:36)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:7000/polyfills.bundle.js:2737:47)
    at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:7000/polyfills.bundle.js:3044:34)
    at invokeTask (http://localhost:7000/polyfills.bundle.js:4085:14)"
}

0 个答案:

没有答案