繁体   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