簡體   English   中英

如何從Nest.js中的服務觸發應用程序關閉?

[英]How to trigger application shutdown from a service in Nest.js?

我正在尋找一種方法來從Nest.js中的服務觸發應用程序關閉,該服務仍然會調用鈎子。

我遇到一種情況,當我在服務中處理消息時,在某些情況下應關閉應用程序。 我曾經拋出未處理的異常,但是當我做這個Nest.js並不要求像鈎子onModuleDestroy甚至關閉掛鈎像onApplicationShutdown這是需要我的情況。

INestApplication調用.close()可以按預期工作,但是如何將其注入到我的服務中呢? 或者也許我可以使用其他一些模式來實現自己的目標?

非常感謝您提供的所有幫助。

您無法注入應用程序。 相反,您可以從服務中發出關閉事件,讓應用程序訂閱它,然后在main.ts觸發實際的關閉:

服務

export class ShutdownService implements OnModuleDestroy {
  // Create an rxjs Subject that your application can subscribe to
  private shutdownListener$: Subject<void> = new Subject();

  // Your hook will be executed
  onModuleDestroy() {
    console.log('Executing OnDestroy Hook');
  }

  // Subscribe to the shutdown in your main.ts
  subscribeToShutdown(shutdownFn: () => void): void {
    this.shutdownListener$.subscribe(() => shutdownFn());
  }

  // Emit the shutdown event
  shutdown() {
    this.shutdownListener$.next();
  }
}

main.ts

// Subscribe to your service's shutdown event, run app.close() when emitted
app.get(ShutdownService).subscribeToShutdown(() => app.close());

在此處查看正在運行的示例:

編輯服務中的Nest關閉

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM