Issue
Main.module.ts
@NgModule({
declarations:[HomeComponent,MasterComponent,],
imports:[
BrowserModule,
FormsModule,
RouterModule.forRoot(MainRoutes)
],
providers:[
{
provide:BaseLogger,
useClass:DBLogger
},
{provide:"1",useClass:DBLogger},
{provide:"2",useClass:ConsoleLogger},
],
bootstrap:[MasterComponent]
})
export class MainModule{
}
***customer.component.ts***
I just injection but provide value not shown in the constructor of the component
@Component({
selector: 'cust-app',
templateUrl: './customer.view.html',
styleUrls: ['./customer.view.css']
})
export class CustomerComponent {
title: string = 'Customer Application';
customerModel:Customer = new Customer();
customerModels:Array<Customer> = new Array<Customer>();
loggerObj: BaseLogger = null;
constructor(_injector: Injector) {
this.loggerObj = _injector.get("1");
-- Show error get is deprecated I got an error here I just want to provide value
I do not know how
to inject
this.loggerObj.Log();
}
}
CustomerApp.logger.ts
---------------------
export interface ILogger{
Log():void;
}
export class BaseLogger implements ILogger{
Log(){
}
}
export class ConsoleLogger extends BaseLogger{
Log(){
console.log('Using Console Logger..');
}
}
export class DBLogger extends BaseLogger{
Log(){
console.log('Using Database Logger');
}
}
export class FileLogger extends BaseLogger{
Log():any{
console.log('Using File Logger');
}
}
Error :
You can see below code I am trying to use the injector in the constructor
but I did not get("1")
I am struggling to do in
get method is deprecated so how to get 1 value from providing in the constructor of component.
what I want if the value of providing which is present in providers:[] of the main module I want
this "1"
but nothing happens
Solution
Finally, I got my answer Here below I gonna step by step to solve this issue
step 1> I apply DBLogger as a type to get()
Ex: constructor(_injector: Injector) {
this.loggerObj = _injector.get<BaseLogger>("1");
this.loggerObj.Log();
}
Note: DBLogger already Present in CustomerApp.logger.ts
step 2: instead of assign "1" or "2" to the parameter I have used one line
export const DB=new InjectionToken("1");
and Apply this DB to the parameter to get<BaseLogger>(DB)
Example :
export class CustomerComponent {
loggerObj: BaseLogger = null;
constructor(_injector: Injector) {
this.loggerObj = _injector.get<BaseLogger>(DB);//
this.loggerObj.Log();
}
step 3: also apply to the provide value also
providers:[
{
provide:BaseLogger,
useClass:DBLogger
},
{provide:DB,useClass:DBLogger}, // here I apply DB instead of "1"
],
Answered By – farukh shaikh
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0