【问题标题】:Injected service is undefined, but works in other classes注入的服务未定义,但可以在其他类中使用
【发布时间】:2017-07-27 23:23:44
【问题描述】:

我很困惑:我通常会在其他服务中注入和使用我的 LoggingService 并且它可以工作。这是我非常简单的 LoggingService:

import { Injectable } from '@angular/core';

@Injectable()
export class LoggingService {
  //[...]  
  logInfo(obj: any) {
    if (this.logging) console.info('[INFO] ' + obj);
  }
}

在以下类中,我的注入服务未定义

interceptor.service.ts

import { LoggingService } from './../logging/logging.service';
import { RequestOptionsArgs, Response } from '@angular/http';
import { Injectable, Injector, OnInit } from '@angular/core';
import { IHttpInterceptor } from '@covalent/http';

@Injectable()
export class InterceptorService implements IHttpInterceptor {

  constructor(private logger: LoggingService) {
    console.log('logger = ' + logger); // UNDEFINED
  }

  onRequest(requestOptions: RequestOptionsArgs): RequestOptionsArgs {
    this.logger.logDebug(requestOptions); // Obviously does not work
    return requestOptions;
  }

  // [...] Other methods
}

app.module.ts

import { InterceptorService } from './services/interceptor/interceptor.service';
import { CovalentHttpModule, IHttpInterceptor } from '@covalent/http';
import { LoggingService } from './services/logging/logging.service';

@NgModule({

  imports: [
    // [...]
    CovalentHttpModule.forRoot({
      interceptors: [{
        interceptor: InterceptorService, paths: ['**'],
      }],
    }),
  ],

  providers: [
    LoggingService,
    InterceptorService,
    // [...]
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这个类与其他类有何不同(注入工作的地方?

我也尝试使用注入器注入服务:

loggingService : LoggingService;
constructor(private injector: Injector) { }
// [...]
loggingService = this.injector.get(LoggingService);

但它总是未定义。我错过了什么?

IHttpInterceptor 类来自以下框架: https://teradata.github.io/covalent/#/components/http

【问题讨论】:

  • 您是否在其他地方注入 ihttpInterceptor 并且它有效?尝试删除它的注入并评论它使用并检查它是否有效。也将logginservice import放在其他之后。

标签: angular dependency-injection


【解决方案1】:

使用 Angular 4.3 的 Httpclient,我最终放弃并编写了自己的拦截器。我遇到的问题可能与 Covalent 的 Interceptor 服务和配置有关。

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多