Nimer Awad
Nimer Awad

Reputation: 4199

How can I inject dependency in custom class?

I'm working on Interceptor that creates an instance of custom class, like:

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {

  constructor(
    @Inject('LOGGING_CONFIG') private config: iLoggingConfig
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
    // get event that caused request
    var event = <MouseEvent>window.event;
    // check if there's no event
    if (event === undefined) return next.handle(req);
    // create request document
    var requsetDocument = new InteractionRequest(this.config, req, event);
    // set request document 
    this.service.setRequest(requsetDocument);
    // continue request
    return next.handle(req);
  }

}

where InteractionRequest needs this object, and I use this class in different places where I have to inject config in each one.

So, I thought if I could inject config directly to InteractionRequest class not to pass it as param.

I tried to inject to class constructor, but it gives me undefined, like:

export class InteractionRequest {
  constructor(
    @Inject('LOGGING_CONFIG') private config: iLoggingConfig
  ) {
   console.log(this.config); // it logs undefined!!
  }
}

Is that doable? if yes; how to do it?

Upvotes: 0

Views: 82

Answers (1)

Numichi
Numichi

Reputation: 1092

I do not understand completely. I may not be able to answer exactly what you want, but I will try.

What is "iLoggingConfig"? Why use "LOGGING_CONFIG"?

"custom class" is a object or a Serivce?

1) "root" Service solution https://angular.io/guide/providers

@Injectable({ providedIn: 'root' }) // not need add to providers
export class iLoggingConfig {
    // ...
}
export class InteractionRequest {
    constructor(private config: iLoggingConfig) {
        console.log(this.config);
    }
}
@NgModule({..., providers: [], ...})
export class AppModule {...}

2) module Service solution

@Injectable() // You have to add to any Module where you would like to use.
export class iLoggingConfig {
    // ...
}
export class InteractionRequest {
    constructor(private config: iLoggingConfig) {
        console.log(this.config);
    }
}
// It can be another module, you will only see it in this and submodules
// In this example, I put it into AppModule, which is equivalent to my first example.
@NgModule({..., providers: [iLoggingConfig], ...})
export class AppModule {...} 

3) const object solution

export const iLoggingConfig = {...};
// or
export const iLoggingConfig = new CustomClass();
import { iLoggingConfig } from 'path/to/i-logging-config.ts'
export class InteractionRequest {
    constructor() {
        console.log(iLoggingConfig);
    }
}

Upvotes: 2

Related Questions