简体   繁体   中英

How to inject component-specific values into a service?

It is clear to me how we can inject a service. We can provide the service either at the module level, or at the component level.

I wish to inject a specific property to the service before that service in turn is injected into my component. The property in question is dependent on my component.

How can this be achieved in Angular 2?

Example:

@Injectable()
export class MyService {
  constructor(myProperty: string) {
    setSomethingUsingMyProperty(myProperty)
  }
}

@Component(..., {providers: [MyService] })
export class MyComponent {
  constructor(myService: MyService) {
    myService.doSomething()
  }
}

If I'd provide the property in the overlying module, I presume Angular can inject the property if I include the @Inject directive. But how can this be achieved at the component level?

You can provide and inject by string name like

@Injectable()
export class MyService {
  constructor(@Inject('someName') myProperty: String) {
    setSomethingUsingMyProperty(myProperty)
  }
}
@Component({..., 
  providers: [MyService, {provide: 'someName', useValue: 'someValue'}] })
export class MyComponent {
  constructor(myService: MyService) {
    myService.doSomething()
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM