Reputation:
Say I have this service and component. I would like to use multiple instances of MySillyService.
@Injectable()
export class MySillyService {
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
vals: Array<MySillyService>;
constructor() {
this.vals = [1,2,3].map(v => {
return this.getSillyService();
});
}
@Inject(MySillyService)
getSillyService(mss: MySillyService){
console.log('getting mss...');
return mss;
}
}
this won't compile because I get this error:
Is there a way to inject a new instance of a service using a method instead of the constructor?
Upvotes: 2
Views: 74
Reputation: 73761
The Injector service can be used to inject a service using a method:
import { Injector } from '@angular/core';
export class AppComponent {
vals: Array<MySillyService>;
mySillyService: MySillyService;
constructor(private injector: Injector) {
this.vals = ['some','dynamic','array'].map(v => this.getSillyService());
}
getSillyService() {
return this.injector.get(MySillyService);
}
injectAnotherInstance() {
this.mySillyService = this.injector.get(MySillyService);
}
}
Upvotes: 1
Reputation: 60596
If you don't really need Angular's management of the instances (single instance) or its dependency injection, you could create just a simple class. Then you can create and pass around how ever many instances of it that you need.
I don't think this is a common technique ... but it should work.
Upvotes: 1
Reputation: 4918
No there isn't. But you can inject multiple instances just by naming them different things:
constructor(private myService1: dataService, private myService2: dataService) { }
Upvotes: 0