使用 Azure Cosmos DB 的用于 MongoDB 的 API 创建 Angular 应用 - 将 CRUD 函数添加至应用Create an Angular app with Azure Cosmos DB's API for MongoDB - Add CRUD functions to the app

本教程包含多个部分,演示了如何通过 Express 和 Angular 创建以 Node.js 编写的新应用,然后将其连接到使用 Cosmos DB 的用于 MongoDB 的 API 配置的 Cosmos 帐户This multi-part tutorial demonstrates how to create a new app written in Node.js with Express and Angular and then connect it to your Cosmos account configured with Cosmos DB's API for MongoDB. 本教程的第 6 部分基于第 5 部分,涵盖以下任务:Part 6 of the tutorial builds on Part 5 and covers the following tasks:

  • 为 hero 服务创建 Post、Put 和 Delete 函数Create Post, Put, and Delete functions for the hero service
  • 运行应用Run the app

先决条件Prerequisites

开始教程的此部分之前,请确保已完成教程第 5 部分的步骤。Before starting this part of the tutorial, ensure you've completed the steps in Part 5 of the tutorial.

提示

本教程介绍生成应用程序的各个步骤。This tutorial walks you through the steps to build the application step-by-step. 若要下载完成的项目,可从 GitHub 上的 angular-cosmosdb 存储库获取完成的应用程序。If you want to download the finished project, you can get the completed application from the angular-cosmosdb repo on GitHub.

向 hero 服务添加 Post 函数Add a Post function to the hero service

  1. 在 Visual Studio Code 中按“拆分编辑器”按钮 并排打开 routes.js 和 hero.service.js 。

    可以看到,routes.js 第 7 行调用的是 hero.service.js 中第 5 行的 getHeroes 函数。See that routes.js line 7 is calling the getHeroes function on line 5 in hero.service.js. 需为 post、put 和 delete 函数进行与此相同的配对。We need to create this same pairing for the post, put, and delete functions.

    Visual Studio Code 中的 routes.js 和 hero.service.js

    首先,请对 hero 服务进行编码。Let's start by coding up the hero service.

  2. 将以下代码复制到 hero.service.js 中 module.exports 函数之前 getHeroes 函数之后的位置。Copy the following code into hero.service.js after the getHeroes function and before module.exports. 此代码:This code:

    • 使用 hero 模型发布新的 hero。Uses the hero model to post a new hero.
    • 查看响应,了解是否存在错误,然后返回状态值 500。Checks the responses to see if there's an error and returns a status value of 500.
    function postHero(req, res) {
     const originalHero = { uid: req.body.uid, name: req.body.name, saying: req.body.saying };
     const hero = new Hero(originalHero);
     hero.save(error => {
       if (checkServerError(res, error)) return;
       res.status(201).json(hero);
       console.log('Hero created successfully!');
     });
    }
    
    function checkServerError(res, error) {
     if (error) {
       res.status(500).send(error);
       return error;
     }
    }
    
  3. 在 hero.service.js 中更新 module.exports,使之包括新的 postHero 函数。In hero.service.js, update the module.exports to include the new postHero function.

    module.exports = {
      getHeroes,
      postHero
    };
    
  4. 在 routes.js 中的 get 路由器之后为 post 函数添加一个路由器。In routes.js, add a router for the post function after the get router. 此路由器一次发布一个 hero。This router posts one hero at a time. 以这种方式安排路由器文件的结构可以清楚地显示所有可用的 API 终结点,将真正的工作留给 hero.service.js 文件。Structuring the router file this way cleanly shows you all of the available API endpoints and leaves the real work to the hero.service.js file.

    router.post('/hero', (req, res) => {
      heroService.postHero(req, res);
    });
    
  5. 运行应用,看是否一切正常。Check that everything worked by running the app. 在 Visual Studio Code 中,保存所有更改,选择左侧的“调试”按钮 ,然后选择“启动调试”按钮

  6. 现在请返回到 Internet 浏览器,打开开发人员工具的“网络”选项卡(在大多数计算机上按 F12 即可)。Now go back to your internet browser and open the Developer tools Network tab by pressing F12 on most machines. 导航到 http://localhost:3000,观察通过网络进行的调用。Navigate to http://localhost:3000 to watch the calls made over the network.

    Chrome 中的“网络”选项卡,显示网络活动

  7. 通过选择“添加新 Hero”按钮添加新的 hero。Add a new hero by selecting the Add New Hero button. 输入“999”作为 ID,“Fred”作为 name,“Hello”作为 saying,然后选择“保存”。Enter an ID of "999", name of "Fred", and saying of "Hello", then select Save. 此时会在“网络”选项卡中看到为新的 hero 发送了 POST 请求。You should see in the Networking tab you've sent a POST request for a new hero.

    Chrome 中的“网络”选项卡,显示 Get 和 Post 函数的网络活动

    现在,让我们回过头来向应用添加 Put 和 Delete 函数。Now let's go back and add the Put and Delete functions to the app.

添加 Put 和 Delete 函数Add the Put and Delete functions

  1. 在 routes.js 中的 post 路由器后添加 putdelete 路由器。In routes.js, add the put and delete routers after the post router.

    router.put('/hero/:uid', (req, res) => {
      heroService.putHero(req, res);
    });
    
    router.delete('/hero/:uid', (req, res) => {
      heroService.deleteHero(req, res);
    });
    
  2. 将以下代码复制到 hero.service.js 中 checkServerError 函数之后的位置。Copy the following code into hero.service.js after the checkServerError function. 此代码:This code:

    • 创建 putdelete 函数Creates the put and delete functions
    • 查看是否已找到 heroPerforms a check on whether the hero was found
    • 进行错误处理Performs error handling
    function putHero(req, res) {
     const originalHero = {
       uid: parseInt(req.params.uid, 10),
       name: req.body.name,
       saying: req.body.saying
     };
     Hero.findOne({ uid: originalHero.uid }, (error, hero) => {
       if (checkServerError(res, error)) return;
       if (!checkFound(res, hero)) return;
    
      hero.name = originalHero.name;
       hero.saying = originalHero.saying;
       hero.save(error => {
         if (checkServerError(res, error)) return;
         res.status(200).json(hero);
         console.log('Hero updated successfully!');
       });
     });
    }
    
    function deleteHero(req, res) {
     const uid = parseInt(req.params.uid, 10);
     Hero.findOneAndRemove({ uid: uid })
       .then(hero => {
         if (!checkFound(res, hero)) return;
         res.status(200).json(hero);
         console.log('Hero deleted successfully!');
       })
       .catch(error => {
         if (checkServerError(res, error)) return;
       });
    }
    
    function checkFound(res, hero) {
     if (!hero) {
       res.status(404).send('Hero not found.');
       return;
     }
     return hero;
    }
    
  3. 在 hero.service.js 中导出新模块:In hero.service.js, export the new modules:

    module.exports = {
      getHeroes,
      postHero,
      putHero,
      deleteHero
    };
    
  4. 更新了代码后,选择 Visual Studio Code 中的“重启”按钮

  5. 刷新 Internet 浏览器中的页面,选择“添加新 Hero”按钮。Refresh the page in your internet browser and select the Add New Hero button. 添加 ID 为“9”、name 为“Starlord”、saying 为“Hi”的新 hero。Add a new hero with an ID of "9", name of "Starlord", and saying "Hi". 选择“保存”按钮保存新 hero。Select the Save button to save the new hero.

  6. 现在请选择 Starlord hero,将 saying 从“Hi”更改为“Bye”,然后选择“保存”按钮。Now select the Starlord hero, and change the saying from "Hi" to "Bye", then select the Save button.

    现在可以在“网络”选项卡中选择 ID 来显示有效负载了。You can now select the ID in the Network tab to show the payload. 可以在有效负载中看到,saying 现在已设置为“Bye”。You can see in the payload that the saying is now set to "Bye".

    Heroes 应用和“网络”选项卡,显示有效负载

    还可以在 UI 中删除某个 hero,看完成删除操作需要多少时间。You can also delete one of the heroes in the UI, and see the times it takes to complete the delete operation. 尝试时,可针对名为“Fred”的 hero 选择“删除”按钮。Try this out by selecting the "Delete" button for the hero named "Fred".

    Heroes 应用和“网络”选项卡,显示完成函数操作的时间

    如果刷新页面,“网络”选项卡会显示获取 hero 的时间。If you refresh the page, the Network tab shows the time it takes to get the heroes. 虽然这里显示的时间很短,但很多情况下,具体时间取决于数据在中国所处的位置,以及能否在靠近用户的区域进行异地复制。While these times are fast, a lot depends on where your data is located in China and your ability to geo-replicate it in an area close to your users. 可以在即将推出的下一教程中详细了解异地复制。You can find out more about geo-replication in the next, soon to be released, tutorial.

后续步骤Next steps

在本教程的此部分,你已完成以下操作:In this part of the tutorial, you've done the following:

  • 向应用添加 Post、Put 和 Delete 函数Added Post, Put, and Delete functions to the app

本教程系列会添加更多的视频,请稍后回来观看。Check back soon for additional videos in this tutorial series.