Daniel
Daniel

Reputation: 607

Injecting Angular2 Service into components base class

I want to create a base class for components to be able to do something common during the life-cycle of the components. I also need the base class to access some service. How do I inject it? Of course I can use a singleton instead of a service, but that would not be very angularish even not typescriptish, I suppose, since singletons are an anti-pattern there. Greets, Daniel

EDIT:

This is what is currently working, but I rather expected to make the ConnectionService @Injectable() and inject it into the RemoteController's constructor like Angular2 docs say, preferably without the necessity to add it to the child components providers list.

The Child Component:

@Component(...)
export class SomeComponent extends RemoteController {
    sendRequest() {
        this.request('something');
    }
}

The Base Class:

export class RemoteController implements OnInit {
    public connection: SocketIOClient.Socket;
    constructor() {
        this.connection = RemoteService.connect('ws://localhost:8500');
    }
    request(name: string) {
        this.connection.emit('request', name);
    }
    ngOnInit() {
        ...
    }
}

The Singleton Solution:

class ConnectionService {
    private sockets: { [key: string]: SocketIOClient.Socket };
    constructor() {
        debugger;
        this.sockets = {};
    } 
    connect(url: string) {
        return (url in this.sockets) ? this.sockets[url] : io.connect(url);
    }
}
let RemoteService = new ConnectionService();

export { RemoteService };

Upvotes: 2

Views: 504

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658037

Angular2 only supports constructor injection. If you have a super class and a sub class and you want to inject to the super class you have to add the constructor parameter to the sub class and forward it to the sub class

export class RemoteController implements OnInit {

    constructor(public connection: SocketIOClient.Socket) {
        this.connection = RemoteService.connect('ws://localhost:8500');
    }
@Component(...)
export class SomeComponent extends RemoteController {
    constructor(connection: SocketIOClient.Socket) {
      super(connection

Upvotes: 1

Related Questions