Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject a service into a component

FYI: using angular2 (2.0.0-alpha.45) & TypeScript (1.6.2)

Trying to create a simple service to inject into a component.

The error I'm getting:

Cannot resolve all parameters for {ComponentName}(?). Make sure they all have valid type or annotations.

Bootstrapping:

bootstrap(App, [ROUTER_PROVIDERS, HTTP_PROVIDERS]);

Service (my-service.ts):

import {Injectable} from 'angular2/angular2';
@Injectable()
export class MyService {
  public doSomething() {}
}

Consuming Component:

import {Component} from 'angular2/angular2';
import {MyService} from './my-service';
export class ListManager{
  constructor(private myService: MyService){
    console.log('myService', myService);
  }
}

Things I've tried

  • In the service:
    • marking/un-marking the service with @Injectable
  • In bootstrapping:
    • Adding/removing MyService into the bootstrapping list of providers
  • In component
    • specifying the service as a provider @Component({providers: [MyService]})
    • specifying the service as a binding @Component({bindings: [MyService]})
like image 619
Brocco Avatar asked Dec 30 '25 01:12

Brocco


2 Answers

I think you would do:

constructor(private myService: MyService){
    console.log('myService', myService);
}

You also have to specify the service as a provider in @Component definition

@Component({
  ...
  providers: [MyService]})
like image 122
Luca Avatar answered Dec 31 '25 17:12

Luca


Try doing this in your component:

import {Component} from 'angular2/angular2';
import {Inject} from 'angular2/core';
import {MyService} from './my-service';

export class ListManager{
  private listService: ListService;

  constructor(@Inject(ListService) listService: ListService){
      console.log('listService', listService);
  }
}

(Pay attention to the new import and @Inject inside the constructor)

Let me know if it worked for you. A plunker will also help isolating the problem.

like image 40
Yaniv Efraim Avatar answered Dec 31 '25 17:12

Yaniv Efraim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!