javascript - 如何从 Nest.js 中的服务触发应用程序关闭?
问题描述
我正在寻找一种方法来从 Nest.js 中的服务触发应用程序关闭,该服务仍将调用钩子。
我有一个案例,当我在服务中处理消息时,在某些情况下这应该关闭应用程序。我曾经抛出未处理的异常,但是当我这样做时,Nest.js 不会调用像我这样的钩子onModuleDestroy
甚至关闭钩子onApplicationShutdown
,这在我的情况下是必需的。
按预期调用.close()
fromINestApplication
工作,但我如何将它注入我的服务?或者也许我可以使用其他一些模式来实现我想要做的事情?
非常感谢您提供的所有帮助。
解决方案
您不能注入应用程序。相反,您可以从您的服务发出一个关闭事件,让应用程序订阅它,然后在您的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());
在此处查看运行示例:
推荐阅读
- php - 将 curl 翻译成 php
- c# - WPF:更改按钮背景和字体不起作用
- python - 在 Sublime Text 上有 Matplotlib,现在它消失了
- java - Java8 forEach 带索引
- java - 如何使用 Unirest 以列表形式获得响应?
- python - 尝试用 Python 创建简单的猜谜游戏?
- python - 如何在 Python 中将字符串布尔值转换为 IF 语句
- android-studio - Quick Docs 不会在 Android Studio 中自动显示
- kubernetes - Kubernetes grpc http 2error
- wpf - 内容为 Null 时隐藏自定义 WPF 按钮