I created a service SocketService, basically it initializes the socket to let the app listen on the port. This service also interacts with some components.
// socket.service.ts
export class SocketService {
constructor() {
// Initializes the socket
}
...
}
I know the code in SocketService's constructor() only starts to run when a component use SocketService.
And usually the code in app.ts looks like this:
// app.ts
import {SocketService} from './socket.service';
...
class App {
constructor () {}
}
bootstrap(App, [SocketService]);
However, I want this service run when the app starts. So I made a trick, just add private _socketService: SocketService
in App's constructor(). Now the code looks like this:
// app.ts (new)
import {SocketService} from './socket.service';
...
class App {
constructor (private _socketService: SocketService) {}
}
bootstrap(App, [SocketService]);
Now it works. The problem is sometimes the code in SocketService's constructor() runs, and sometimes not. So how should I do it correctly?