angular2: inject generic service?

1.2k Views Asked by At

What's the recommended approach for injecting a generic service into a component? For instance, suppose you've got this:

export class Service<T>{ ... }

Now, lets suppose we've also got a class named Person:

export class Person { ... }

And I'd like to inject it in a component:

@Component({
  selector: "frt-X",
  templateUrl: "...",
  providers: [Service<Person>] }) <--ERROR
export class MyComponent {
  constructor(private service: Service<Person>) { }
}

I was wondering if there's a way to be specific about the provider type. Currently, and since templates aren't transformed into JavaScript, I'm simply passing Service.

EDIT: I'm trying to give more info about my scenario.

Suppose you've got two different routes, mapped into 2 different components. Lets call them A and B. Now, suppose that each of these componentes has an internal secondary router outlet for loading different componentes. Lets say that:

A


C | outlet: can load D or E

B


F | outlet: can load G or H

Now, let's say that A needs to be notified when D or E loads an object of type Person and that B needs to be notified when G or H loads an object of type Car. In order to achieve this, I'm using a service which gets injected in the parent and child components (I'm following the instructions found on the official documentation). I've thought about using generics to specify the type of object that gets loaded. The code is the same for both cases, but in one place, the inner component loads Person objects while in the other, the inner components load Car objects.

Sure, I could just use object, but since TypeScript supports generics, I thought that I should use it in order to get better intellisense and more "type safety".

Thanks.

Regards, Luis

0

There are 0 best solutions below