0

我正在尝试使用 nestjs 构建自定义 Alexa 网络服务。如果我尝试从 AlexaController 调用 RequestHandler 中的服务,它不起作用,因为 this. 那里不可用(如果我在 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 中可见?有什么建议吗?提前致谢

4

1 回答 1

1

Javascript 中的this关键字可以指代不同的事物,具体取决于访问它的范围。对于 Javascript 开发人员来说,这是一个常见的混淆来源,this如果您快速搜索一下 Google,您可以阅读大量有关范围的内容。

话虽如此,自从在 Javascript 中引入箭头函数以来,许多由此引起的常见错误现在都已“解决”,因为它们会自动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();
        },
      };
于 2020-09-15T16:30:53.117 回答