Nice programing

Angular 2에서 앱이 시작될 때 서비스를 실행하는 방법

nicepro 2020. 12. 3. 19:43
반응형

Angular 2에서 앱이 시작될 때 서비스를 실행하는 방법


서비스 SocketService를 만들었는데 기본적으로 앱이 포트에서 수신 할 수 있도록 소켓을 초기화합니다. 이 서비스는 일부 구성 요소와도 상호 작용합니다.

// socket.service.ts

export class SocketService {
    constructor() {
        // Initializes the socket
    }
    ...
}

SocketService의 constructor () 코드는 구성 요소가 SocketService를 사용할 때만 실행되기 시작한다는 것을 알고 있습니다.

일반적으로 app.ts의 코드는 다음과 같습니다.

// app.ts

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

그러나 앱이 시작될 때이 서비스를 실행하고 싶습니다. 그래서 트릭을 만들었고 private _socketService: SocketServiceApp의 constructor ()를 추가 했습니다. 이제 코드는 다음과 같습니다.

// app.ts (신규)

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

이제 작동합니다. 문제는 때때로 SocketService의 constructor () 코드가 실행되지 않는 경우도 있습니다. 그렇다면 어떻게 올바르게해야합니까? 감사


SocketService생성자 의 논리를 대신 메서드로 이동 한 다음 기본 구성 요소의 생성자에서 호출하거나ngOnInit

SocketService

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

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

Stuart의 대답은 올바른 방향을 가리 키지 만 APP_INITIALIZER에 대한 정보를 찾기가 쉽지 않습니다. 짧은 버전은 다른 애플리케이션 코드가 실행되기 전에 초기화 코드를 실행하는 데 사용할 수 있다는 것입니다. 잠시 검색해 여기여기 에서 설명을 찾았 는데, 웹에서 사라지는 경우를 대비해 요약하겠습니다.

APP_INITIALIZER는 앵귤러 / 코어로 정의됩니다. 다음과 같이 app.module.ts에 포함합니다.

import { APP_INITIALIZER } from '@angular/core';

APP_INITIALIZER는 ApplicationInitStatus 서비스를 참조 하는 OpaqueToken (또는 Angular 4 이후의 InjectionToken)입니다. ApplicationInitStatus는 다중 공급자 입니다. 여러 종속성을 지원하며 공급자 목록에서 여러 번 사용할 수 있습니다. 이렇게 사용됩니다.

@NgModule({
  providers: [
    DictionaryService,
    {
      provide: APP_INITIALIZER,
      useFactory: (ds: DictionaryService) => function() {return ds.load()},
      deps: [DictionaryService],
      multi: true
    }]
})
export class AppModule { }

This provider declaration tells the ApplicationInitStatus class to run the DictionaryService.load() method. load() returns a promise and ApplicationInitStatus blocks the app startup until the promise resolves. The load() function is defined like this.

load(): Promise<any> {
  return this.dataService.getDiscardReasons()
  .toPromise()
  .then(
    data => {
      this.dictionaries.set("DISCARD_REASONS",data);
    }
  )
}

Set up like that the dictionary gets loaded first and the other parts of the app can safely depend on it.

Edit: Be aware that this will increase the up-front load time for you app by however long the load() method takes. If you want to avoid that you could use a resolver on your route instead.


Also see APP_INITIALIZER, which is described as;

A function that will be executed when an application is initialized.


Try Creating service constructor & then call it in ngOnInit() of your component.

  • Service Module

 export class SocketService {
    constructor() { }
        getData() {
            //your code Logic
        }
}

  • Component

export class AppComponent {
    public record;  
    constructor(private SocketService: DataService){ }
    ngOnInit() {        
        this.SocketService.getData()
        .subscribe((data:any[]) => {
            this.record = data;
        });   
  }  
}       

Hope this Helps.

참고URL : https://stackoverflow.com/questions/35191617/how-to-run-a-service-when-the-app-starts-in-angular-2

반응형