Angular 2 service constructor with parameter

2019-03-31 13:11发布

I want to initialize a service with argument. Each component will have its own service instance.

@Injectable()
export class LoggingService {
  constructor( @Inject('group') @Optional() public group?: string) {
    this.group = group;
  }
}

It can be injected in to the component like this :

@Component({
    selector: 'test',
    templateUrl: 'test.component.html',
    providers: [
        LoggingService,
        { provide: 'group', useValue: 'Anythings goes here' }
    ]
})
export class TestComponent implements OnInit {
    constructor(private logger : LoggingService) {

    }
}

Above functionality is working fine for me.

I also want to inject LoggingService into TimeCalculationService. How I can provide 'group' from TimeCalculationService

@Injectable()
export class TimeCalculationService {

    constructor(private logger : LoggingService) {

    }
}

Is there anything like this

@Injectable({
    providers : [
        { provide: 'group', useValue: 'Anythings goes here' }
    ]
})

0条回答
登录 后发表回答