2016-03-02 84 views
0

我有一个应用程序控制器有2个方法。在第一种方法中,我访问数据库并检索表单的下拉元素列表。我将检索到的元素存储在类级变量中。在第二种方法中,如果出现错误,它将显示表单,否则它会显示结果。问题是我的类的变量返回空。请求之间应用程序类变量不可用

class Application extends Controller { 

     var appList = Seq[AppDetail]() 
     var countryList = Seq[Country]() 

    def home(page:Int,filter: String): Action[AnyContent] = Action.async { implicit request => 

    val futures = for { 
      appDetails <- AppDetailsDAO.listAll() //DB retrieve 
      countries <- CountriesDAO.listAll() //DB retrieve 
      } yield (appDetails, countries) 

      futures.map{case (appDetails, countries) => { 
      appList = appDetails 
      countryList = countries 
      Ok(appList, countryList) 
      } 

     } 

     def result(page:Int, filter: String): Action[AnyContent] = Action.async { implicit request => 

    analyticForm.bindFromRequest.fold(
     formWithErrors => { 
     Future.successful(BadRequest(html.home(formWithErrors, appList, countryList)) //appList, countryList returns empty 
     }, 
     analyticData => { 
    Ok(appList, countryList) //appList, countryList returns empty 
     } 
    } 
    } 

回答

1

Play是一个RESTful框架。这意味着,除其他外,您不应在两个请求之间共享信息。请求始终是无状态的。

要解决您的问题,您只需在您的两个操作中获取appListcountryList。还要删除控制器中的两个var。尽可能避免scala中的可变变量(尽管如此,它们可能有用)。请参阅Daniel C. Sobral在the difference between var and val上的回答。

未经测试的提前代码:

class Application extends Controller { 

    def home(page:Int,filter: String): Action[AnyContent] = Action.async { implicit request => 
    fetchDb.map{case (appDetails, countries) => { 
     appList = appDetails 
     countryList = countries 
     Ok(appList, countryList) 
    }} 
    } 

    def result(page:Int, filter: String): Action[AnyContent] = Action.async { implicit request => 
    fetchDb.map{case (appDetails, countries) => { 
     analyticForm.bindFromRequest.fold(
     formWithErrors => { 
      BadRequest(html.home(formWithErrors, appList, countryList)) 
     }, 
     analyticData => { 
      Ok(appList, countryList) //appList, countryList returns empty 
     } 
    ) 
    }} 
    } 

    def fetchDb = { 
    val fAppDetails = AppDetailsDAO.listAll() 
    val fCountries = CountriesDAO.listAll() 

    for { 
     appDetails <- fAppDetails 
     countries <- fCountries 
    } yield (appDetails, countries) 
    } 
} 

旁注:你可能注意到,我在外面fetchDb的理解力创造Future实例。这是因为理解只是嵌套平面地图的另一种表示。这意味着countries将不会运行,直到appDetails已完成。期货将连续运行。如果你把它们放在理解之外,它们将平行运行。

+0

你的回答很清楚。感谢您花时间解释它。 – binshi

相关问题