玩框架2.1 - 无法找到一个隐含的ExecutionContext(Play Framework

2019-08-17 01:40发布

我打电话这样的Web服务:

WS
  .url(url)
  .get
  .map { response => // error occurs on this line
    response.status match {
      case 200 => Right(response.json)
      case status => Left(s"Problem accessing api, status '$status'")
  }
}

完整的错误: Error: Cannot find an implicit ExecutionContext, either require one yourself or import ExecutionContext.Implicits.global

Answer 1:

根据这个问题 ,它是固定的文档。 我需要添加以下导入:

import play.api.libs.concurrent.Execution.Implicits._


Answer 2:

由于播放2.4你可以注入默认execution context通过Guice的依赖:注入。

class Foo @Inject()()(implicit ec:ExecutionContext) {

def bar() = {
   WS.url(url)
     .get
     .map { response => // error occurs on this line
       response.status match {
         case 200 => Right(response.json)
         case status => Left(s"Problem accessing api, status '$status'")
     }
   }
}


Answer 3:

另一种选择:

import scala.concurrent.ExecutionContext.Implicits.global


文章来源: Play Framework 2.1 - Cannot find an implicit ExecutionContext