user5047085
user5047085

Reputation:

Injecting a service using a method instead of the constructor

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:

enter image description here

Is there a way to inject a new instance of a service using a method instead of the constructor?

Upvotes: 2

Views: 74

Answers (3)

Martin Parenteau
Martin Parenteau

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

DeborahK
DeborahK

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

David Anthony Acosta
David Anthony Acosta

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

Related Questions