Angular 2 service constructor with parameter

你。 提交于 2019-12-21 05:41:20

问题


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' }
    ]
})

来源:https://stackoverflow.com/questions/49795615/angular-2-service-constructor-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!