如何使用Angular JS获取POST请求的响应?

时间:2017-04-26 11:29:13

标签: javascript angularjs node.js post asynchronous

我正在使用node,express,mongoose作为前端的后端和角度js。我正在使用表单发送帖子请求。

<div class="alert alert-success" ng-show="success">
  {{success}}
</div>

<div class="alert alert-danger" ng-show="error">
  {{error}}
</div>

  <form id="newCategory" ng-submit="submit()">
    <div class="row">
      <div class="col-md-4">
        {{mySubmit}}
        <div class="form-group">
          <input id="name" name="name" type="text"
            placeholder="Name" class="form-control input-md"
            ng-model="catName">
        </div><!-- ./form-group -->

      </div><!-- ./col -->

      <div class="form-group">
       <input type="submit" name="submit" value="submit" class="btn btn-primary">
      </div><!-- ./form-group -->

    </div><!-- ./row -->
  </form>

其控制者:

  fetchModule.controller('CatsNewCtrl', ['$scope', '$rootScope', 'Request',
    function($scope, $rootScope, Request) {
      // Root Scope
      $rootScope.heading  = 'Categories';
      $rootScope.heading2 = 'new';
      $rootScope.newLink  = undefined;

      $scope.catName = "";
      $scope.submit = function() {
        Request.post('/category', { name  : $scope.catName })
          .then(function(data) {
            $scope.success = data.msg;
          })
          .catch(function(status) {
            $scope.error = "Error: " + status;
          });
        return false;
      };
  }]);

结果什么都没有,我不知道我哪里错了!这项服务工作正常,事实上我能够控制日志结果,但我无法在范围内设置它。

(function() {
  let fetchModule = angular.module('fetchModule', []);

  /**
   * A Service for Requests.
   */
  fetchModule.service('Request', ['$http', function($http) {
    /**
     * Get's content of a specific URL.
     * @param {String} url - URL to GET.
     * @return {Promise} Promise resolves with contents or rejects with an error.
     */
    this.get = function(url) {
      // Promise
      return new Promise((resolve, reject) => {
        $http.get(url)
          .success(result => {
            resolve(result);
          })
          .error((err, status) => {
            reject(err);
          });
      });
    };

/**
 * Get's content of a specific URL.
 * @param {String} url - URL to GET.
 * @param {String} data - Data to post.
 * @return {Promise} Promise resolves with contents or rejects with an error.
 */
this.post = function(url, data) {
  // Promise
  return new Promise((resolve, reject) => {
    $http.post(url, data)
      .success((data, status, headers, config) => {
        resolve(data);
      })
      .error((data, status, headers, config) => {
        resolve(status);
      });
  });
};

请帮助我只是一个有角度的启动器。

2 个答案:

答案 0 :(得分:2)

您在$http中使用反模式包裹Promise,因为$http本身会返回一个承诺。

此外,由于全局Promise超出了角度上下文,因此无论何时更改范围,都需要通知角度以运行摘要来更新视图。使用角度承诺情况并非如此。

Request.post更改为:

this.post = function(url, data) {  
  return $http.post(url, data);
};

在控制器中,返回的对象与属性data中的服务器保存数据存在细微差别

$scope.submit = function() {
    Request.post('/category', { name  : $scope.catName })
      .then(function(resp) {
        $scope.success = resp.data.msg;
      })
      .catch(function(err) {
        $scope.error = "Error: " + err.status;
      });
    return false;
  };

请注意,$http方法.success().error()已弃用

答案 1 :(得分:0)

    scope.submit = function() {
    $http({
      url:'/category', 
      method:'POST'
      data:{ name  : $scope.catName },
      headers: {'Content-Type': 'application/json'},
     })
      .then(function(resp) {
        $scope.success = resp.data.msg;
      },function(error){
        $scope.error = "Error: " + err.status;}
      )};

不要返回false,因为它是一个回调函数。而不是使用catch块使用&#34;功能块&#34;像上面一样。

我改进了解决方案。如果它有效,您可以重构它以将重用的代码移动到您的服务中。不要错过在控制器中注入$ http。

相关问题