亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以在視圖控制器文件中為每個頁面創建一個通用的變量嗎?

我可以在視圖控制器文件中為每個頁面創建一個通用的變量嗎?

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 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號