【问题标题】:Nodejs | Exhange Data Between Controllers节点 |在控制器之间交换数据
【发布时间】:2020-07-06 07:25:43
【问题描述】:

我有我的 PlantsController,我可以在其中获得这样的植物:

function getAll() {
  const plants= HttpRequestPromise.get(config.ApiURL+'allPlants', config.head);
  return plants;
}

export class PlantsController {
  ...
  public getPlants() {
    return async (req: Request, res: Response, next?: NextFunction): Promise<Response> => {
      try {
        const plants = await getAll();
        return res
          .status(OK)
          .send(plants);
      } catch (e) {
        next(e);
      }
    };
  }
  ...
}
export default new PlantsController();

我有 PlantedActivitiesController,在那里我得到了 PlantedActivities 像这样:

import plantsController from '../plants/plants.controller';
export class PlantedActivitiesController {
  ...
  public getPlantedActivities(){
    return async (req: Request, res: Response, next?: NextFunction): Promise<Response> => {
      try {


        var plants = ?  // How can i get the plants from PlantsController?
                        // plantsController.get...?

        ...


      } catch (e) {
        next(e);
      }
    };
  }
  ...
}

那么,我怎样才能让植物进入我的 PlantedActivitiesController?

【问题讨论】:

    标签: node.js angular promise async-await


    【解决方案1】:

    找到了:

    我这样创建了一个 getPlantsHelper:

    function getAll() {
      const plants= HttpRequestPromise.get(config.ApiURL+'allPlants', config.head);
      return plants;
    }
    export class PlantsController {
      ...
    
      //-----------
      public getPlantsHelper(){
        return getAll()
      }
      //-----------
    
      public getPlants() {
        return async (req: Request, res: Response, next?: NextFunction): Promise<Response> => {
          try {
            const plants = await getAll();
            return res
              .status(OK)
              .send(plants);
          } catch (e) {
            next(e);
          }
        };
      }
      ...
    }
    

    然后我在 PlantedActivities 中做了:

    activeSeeds = await plantsController.getPlantsHelper();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多