将服务注入网关 - NestJS

时间:2021-04-28 20:05:25

标签: typescript websocket nestjs nestjs-gateways

我对 nestjs 完全陌生,并尝试将服务注入网关。无法让它工作。以下是代码,

#notification.gateway.ts

@WebSocketGateway()
export  class  NotificationsGateway implements  OnGatewayConnection {
    constructor(private  notificationService: NotificationsService) {}
    
    afterInit(server: any) {
        this.notificationService.server = server;
    }
}

#notification.service.ts

@Injectable()
export  class  NotificationsService {
    public  server: Server = null;
        
    // Removing the inject model line makes the service available in the gateway
    constructor(
        @InjectModel(Notification.name) 
        private  notificationModel: Model<NotificationDocument>
    ) {}
}

#notifications.module.ts

import { TenancyModule } from '../tenancy';

@Module({
  imports: [
    TenancyModule.forFeature([
      { name: Notification.name, schema: NotificationSchema },
    ]),
  ],
  providers: [NotificationsService, NotificationsGateway]
})
export class NotificationsModule {}

出现以下错误,

TypeError: Cannot set property 'server' of undefined
    at NotificationsGateway.afterInit (c:\notifications\notifications.gateway.js:25:41)

删除服务构造函数中的 InjectModel 使服务可用,但我希望模型能够持久化通知。

任何有关如何解决此问题的帮助都非常感谢。谢谢。

0 个答案:

没有答案