How to run a service when the app starts in Angular 2

前端 未结 4 1211
暗喜
暗喜 2020-12-12 15:50

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.

/

4条回答
  •  被撕碎了的回忆
    2020-12-12 15:59

    Move the logic in your SocketService constructor to a method instead and then call that in your main component's constructor or ngOnInit

    SocketService

    export class SocketService{
        init(){
            // Startup logic here
        }
    }
    

    App

    import {SocketService} from './socket.service';
    ...
    class App {
        constructor (private _socketService: SocketService) {
            _socketService.init();
        }
    }
    bootstrap(App, [SocketService]);
    

提交回复
热议问题