简体   繁体   中英

How to inject different service token in the same component?

I have component A , B , C and service S .

A and B change a value in service S .

Component C are used twice in different places of the website, so it needs to read different value from service S .

In two component C , I want one uses token tokenFromA , another uses tokenFromB .

How to inject different service token in the same component? Thanks

// Service S

export class Service {
    text:string = '';
}

// Component C

@Component({
    selector: 'c-component',
    providers: [provide("tokenFromA", {useClass: Service})],
    template: `
        <h1>App</h1>
    `
})
export class ComponentC {
    constructor(@Inject('tokenFromA') service:Service) {
    }
}

As far as I know this is only supported for tests by overrideProviders() of the TestComponentBuilder .

It's also possible to request instances directly

constructor(private _injector:Injector) {
  var bar = _injector.get('bar');
  var bar2 = _injector.get('bar2');
}

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