为了账号安全,请及时绑定邮箱和手机立即绑定

我可以在视图控制器文件中为每个页面创建一个通用的变量吗?

我可以在视图控制器文件中为每个页面创建一个通用的变量吗?

12345678_0001 2023-09-21 17:02:57
我的应用程序中有一个 viewController 文件,我将在其中将变量传递到应用程序的前端。但是,我需要在每个页面中添加某些变量。有没有办法将变量传递到每个页面,而不是一遍又一遍地重复我的代码?在下面的示例中,我定义了cruiseLinesfor exports.getIndex。exports.aboutUs但我在和中有完全相同的代码exports.shipDetails,依此类推。任何帮助,将不胜感激。谢谢你!exports.getIndex = async (req, res, next) => {  // 1) Get tour data from Collection  const ships = await Ship.find().sort({ shipName: 1 });  const cruiseLines = await Ship.distinct('cruiseLine');  const reviewCount = await Review.countDocuments();  // 2) Build template  // 3) Render the template from the tour data from step 1  res.status(200).render('main', {    title: 'Welcome',    ships,    reviewCount,    cruiseLines,  });};
查看完整描述

1 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

您可以创建一个工厂服务并在代码中使用它。像这样的东西。


// ShipSevice.js

const getData = async () => { // you can rename the method

 try {

   const ships = await Ship.find().sort({ shipName: 1 });

   const cruiseLines = await Ship.distinct('cruiseLine');

   const reviewCount = await Review.countDocuments();

   return { ships, cruiseLines, reviewCount }

 } catch(err) {

   return {}

 }

}


module.exports = { getData }


const { getData } = require('relative-path/ShipSevice');


exports.getIndex = async (req, res, next) => {

  try {

    // 1) Get tour data from Collection

    const { ships, cruiseLines, reviewCount } = await getData()

    // 2) Build template

    // 3) Render the template from the tour data from step 1


    res.status(200).render('main', {

      title: 'Welcome',

      ships,

      reviewCount,

      cruiseLines,

    });

  } catch(err) {

    res.status(400).json({ message: 'failed to fetch the'})

  }

};


查看完整回答
反对 回复 2023-09-21
  • 1 回答
  • 0 关注
  • 45 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信