NestJS并询问SDK服务注入

问题描述

我正在尝试使用nestjs构建自定义的Alexa Web服务。 从AlexaController,如果我尝试在RequestHandler内调用服务,则此操作将不起作用。在那里不可用(如果我在requestHandler内尝试console.log(this),我看到{canHandle,handle}),服务器返回我该服务未定义。这是我的控制器:

import { Controller,HttpCode,Post,Req } from "@nestjs/common";
import {
  ErrorHandler,HandlerInput,RequestHandler,SkillBuilders,} from "ask-sdk-core";
import { Response } from "ask-sdk-model";
import { Request } from "express";
import { MessagesService } from "src/services/messages/messages.service";

@Controller("alexa")
export class AlexaController {
  constructor(private myService: MessagesService) {}

  @Post()
  @HttpCode(200)
  async alexaSkill(@Req() req: Request) {
    let skill = SkillBuilders.custom()
      .addRequestHandlers(
        this.LaunchRequestHandler // welcome
      )
      .addErrorHandlers(this.ErrorHandler)
      .create();

    return skill
      .invoke(req.body)
      .then((res) => {
        return res;
      })
      .catch((err) => {
        console.log(err);
      });
  }

  LaunchRequestHandler: RequestHandler = {
    canHandle(handlerInput: HandlerInput): boolean {
      return handlerInput.requestEnvelope.request.type === "LaunchRequest";
    },handle(handlerInput: HandlerInput): Response {
      const speechText = "Welcome to the Alexa Skills Kit,you can say hello!";

      // here I want to call this.myService to do something.
      this.myService.something("hi Alexa");
      // it returns me this error: cannot call something of undefined

      return handlerInput.responseBuilder
        .speak(speechText)
        .reprompt(speechText)
        .withSimpleCard("Hello World",speechText)
        .getResponse();
    },};

  ErrorHandler: ErrorHandler = {
    canHandle(handlerInput: HandlerInput,error: Error): boolean {
      return true;
    },handle(handlerInput: HandlerInput,error: Error): Response {
      console.log(`Error handled: ${error.message}`);

      return handlerInput.responseBuilder
        .speak("Sorry,I can't understand the command. Please say again.")
        .reprompt("Sorry,I can't understand the command. Please say again.")
        .getResponse();
    },};
}

这是我的AlexaModule:

import { Module } from "@nestjs/common";
import { MessagesService } from "src/services/messages/messages.service";
import { AlexaController } from "./alexa.controller";

@Module({
  controllers: [AlexaController],providers: [MessagesService],})
export class AlexaModule {}

如何使该服务在该RequestHandler内部可见?有什么建议吗? 预先感谢

解决方法

JavaScript中的this关键字可以根据访问位置的范围来引用不同的内容。对于Javascript开发人员来说,这是造成混乱的常见原因。如果您使用快速的Google,可以阅读大量关于this范围的内容。

话虽这么说,由于Java中引入了箭头功能,许多由此引起的常见错误已被“解决”,因为它们会自动从外部范围(通常是您自己的范围)中捕获this上下文追。

尝试使用箭头函数而不是常规函数重写处理程序:

LaunchRequestHandler: RequestHandler = {
        canHandle: (handlerInput: HandlerInput) => {
          return handlerInput.requestEnvelope.request.type === "LaunchRequest";
        },handle: (handlerInput: HandlerInput) => {
          const speechText = "Welcome to the Alexa Skills Kit,you can say hello!";
    
          this.myService.something("hi Alexa");
    
          return handlerInput.responseBuilder
            .speak(speechText)
            .reprompt(speechText)
            .withSimpleCard("Hello World",speechText)
            .getResponse();
        },};