【问题标题】:Mean stack Loopback update平均堆栈环回更新
【发布时间】:2019-07-29 21:04:19
【问题描述】:

抱歉,如果这很简单,我对环回/后端比较陌生,

我正在尝试使用以下代码更新现有数据库记录 ID 和名称。 HTML 文件

<div>
  <h1>COMPANY DETAILS</h1>
</div>
<div>
  <div>
    <table>
      <thead>
        <tr>
          <th>Company Name</th>
          <th>Company Code</th>
          <th>Remove</th>
          <th>Edit</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input class="form-control" ng-model="newCompany.name"></td>
          <td><input class="form-control" ng-model="newCompany.id"></td>
          <td><button class="btn btn-primary" ng-click="add()">Add</button></td>
          <td><button class="btn btn-info" ng-click="update()">Update</button></td>
        </tr>
        <tr ng-repeat="company in companies | orderBy:'+name'">
          <td>{{company.name}}</td>
          <td>{{company.id}}</td>
          <td><button class="btn btn-danger" ng-click="remove(company.id)">Remove</button> </td>
          <td><button class="btn btn-warning" ng-click="edit(company)">Edit</button> </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>// This is just a sample script. Paste your real code (javascript or HTML) here.

if ('this_is'==/an_example/){of_beautifier();}else{var a=b?(c%d):e[f];}

JS 文件

'use strict';

/**
 * @ngdoc function
 * @name abcApp.controller:CompanyCtrl
 * @description
 * # CompanyCtrl
 * Controller of the abcApp
 */
angular.module('abcApp')
  .controller('CompanyCtrl', ['$scope', 'Company', function ($scope, Company) {
      $scope.newCompany = { 'id': '', 'name': '' };
      $scope.companies = [];
      Company
          .find()
          .$promise
          .then(function (results) {
              $scope.companies = results;
          });

      $scope.update = function (company) {
          company.findById({ id: company })
            .$promise
            .then(function () {                  
                $scope.company.id = 13.40;
                console.log(company.id);
           $scope.company.$save();
       });
      };

      $scope.edit = function (company) {
          $scope.newCompany = { id: company.id, name: company.name };
      }
      $scope.add = function () {
          Company.create($scope.newCompany, function (company) {
              $scope.newCompany = { 'id': '', 'name': '' };
              Company
                  .find()
                  .$promise
                  .then(function (results) {
                      $scope.companies = results;
                  });

          }, function (errorResponse) {
              console.log(errorResponse);
          });
      };

      $scope.remove = function (cid) {
          Company.deleteById({ id: cid })
           .$promise
              .then(function () {
                  console.log('deleted');
                  Company
                          .find()
                          .$promise
                          .then(function (results) {
                              $scope.companies = results;
                          });
              });
      }
  }]);

$scope.edit 函数将公司 ID 和名称放入两个文本框中,$scope.update 函数用于更新数据库记录,编辑函数工作正常但是我的 $scope.update 出现问题,当我单击更新按钮,我在浏览器控制台中收到以下错误。

无法设置未定义或空引用的属性“名称”

很抱歉,很长的帖子,任何帮助将不胜感激

【问题讨论】:

    标签: javascript angularjs mean-stack loopbackjs


    【解决方案1】:

    看起来你正在混合客户端代码和服务器端代码,$scope.edit 工作的原因是因为它只包含客户端代码。

    Mongoose 调用(Collection.create、Collection.find ...)应该是服务器端的。


    在您的情况下,我将如何使用 MEAN 堆栈:

    Mongo 是您的数据库,它包含您的文档和集合。

    Express 用于使用 http 调用将您的请求从客户端中继到 Mongo。

    Angular 是客户端框架,您的 JS 客户端代码将主要驻留在 Angular 控制器中。


    示例:

    我们想要数据库中的所有胡萝卜。

    客户端(JS):

    angular.module('abcApp')
      .controller('myCarotCtrl', [dependencies,
      function(dependencies) {
         $scope.result = '';
         $scope.getCarrots = function() {
             $http.get('/carrots').
             then(function(data) {
                  //Called when the request is successful
                  $scope.result = data;
             },
             function(error) {
                 //Called when the request failed
                 console.log(error)
             }
         }
      }]);
    

    客户端(HTML):

    <div ng-controller="myController" ng-init="getCarrots()">{{result}}</div>
    

    服务器端:

    //assuming express and mongoose have been required/initialized
    //using Express to route the requests
    //In this exemple request is not used because will dont need parameters
    app.get('/carrots', function(request, response) {
        //Use mongoose to access your Carot Collection
        //{} is all documents in the collection
        Carot.find({}, function(err, documents) {
            //send back the documents to the client once they have been found
            response.status(200).send(document);
        });
    });
    

    我无法测试上面的代码,但我认为它会给你一些关于整个堆栈如何工作的想法。

    【讨论】:

    • 谢谢,我对 mongo/mongoose 很不熟悉,我的数据库是 MySQL,我使用 loopback 来搭建 express 并创建一个后端应用程序。这是服务器端 company.js 代码
    • module.exports = function(Company) { Company.SaveChanges = function(id,name,cb){ Company.exists(id,function(err,exists){ if(err){ cb( null,"error"); }else{ if (exists) { Company.updateAll({id: id}, {name:name}, function(err,obj){ cb(null, "success"); }); }else{ Company.create({id: id, name: name},function(err,obj){ cb(null, "success"); }); } } }); }
    • Company.remoteMethod( 'SaveChanges', { 接受:[{arg: 'id', type: 'String'}, {arg: 'name', type:'String'}], 返回: [{arg: 'status', type: 'String'}] } ); };我认为它现在更清楚,而不是使用 http.get 环回 $scope.prod0 = Product.findById({ id: 0 });阅读和 $scope.product.$save();但是为了保存,我需要用这些调用更新服务端模型,对吗?谢谢保罗
    【解决方案2】:

    company.findById({ id: company })

    这是一个错字吗? company 中的大写 C?我认为它应该类似于我在https://github.com/strongloop/loopback-example-angular/blob/master/client/js/controllers/todo.js#L7-L8的示例

    【讨论】:

    • 是的,你是对的,但是我的代码仍然存在问题,但这肯定会有所帮助。保罗
    【解决方案3】:

    你的 $scope.update 函数在很多方面都是错误的。首先是因为它希望您发送公司参数,但您正在使用空参数调用方法。

    这是你的方法:

    $scope.update = function (company) {
      company.findById({ id: company })
        .$promise
        .then(function () {                  
            $scope.company.id = 13.40;
            console.log(company.id);
            $scope.company.$save();
      });
    

    };

    这是你的 html

    <td><button class="btn btn-info" ng-click="update()">Update</button></td>
    

    “company”参数未定义,因此您的控制台会给您一条错误消息(您正在为 findById id 参数使用未定义的值 - “id: company”)。

    如果您想像这样调用更新方法,那么您可以使用 $scope.newCompany 变量代替公司参数,该变量在您单击编辑按钮后已经包含您要使用的数据。话虽如此,您的更新方法应该是这样的:

    $scope.update = function () {
      Company.findById({ id: $scope.newCompany.id })
        .$promise
        .then(function (company) {
          console.log(company);
          //$scope.company.$save();
        });
    };
    

    要注意的第二件事是您不需要编写远程“保存”方法(除非您编写它是为了练习)。 Loopback 已经为您生成了 CRUD 方法。因此,如果您想从客户端更新您的模型,请使用“upsert”方法或最适合您需求的类似方法。有关服务器上可用方法的列表,请参阅 http://localhost:3000/explorer

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多