简体   繁体   English

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

[英]How can I get the response of a POST request using Angular JS?

I am using node, express, mongoose for backend and angular js for front-end. 我在后端使用node,express,猫鼬,在前端使用angular js。 I am sending a post request using a form. 我正在使用表格发送帖子请求。

<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>

Its controller: 它的控制器:

  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;
      };
  }]);

Result is nothing, I don't know where am I going wrong! 结果什么都没有,我不知道我要去哪里错了! This service is working fine in fact I was able to console log the result but I am unable to set it on scope. 该服务运行正常,实际上我可以控制台记录结果,但无法在作用域上进行设置。

(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);
      });
  });
};

Please help I am just an angular starter. 请帮助我,我只是一个有角度的初学者。

You are using an anti-pattern wrapping $http in Promise since $http itself returns a promise. 您正在Promise中使用反模式包装$http ,因为$http本身会返回一个承诺。

In addition, since global Promise is outside of angular context, whenever it changes the scope angular needs to be notified to run a digest to update the view. 另外,由于全局Promise在角度上下文之外,因此每当更改范围时,都需要通知角度来运行摘要以更新视图。 Using angular promises this is not the case. 使用角度承诺不是这种情况。

Change Request.post to: Request.post更改为:

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

In controller there is a minor difference in that the object returned holds the data from server in a property 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;
  };

Note that $http methods .success() and .error() are deprecated 请注意,不建议使用$http方法.success().error()

    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;}
      )};

Don't return false, because it is a callback function. 不要返回false,因为它是一个回调函数。 Instead of using catch block use "function-block" like above. 代替使用catch块,使用上面的“ function-block”。

I have improved the solution. 我已经改善了解决方案。 If it works, can you refactore it to move reused code to your service. 如果可行,您是否可以对其进行重构以将重用的代码移至服务中。 Dont miss to inject $http in your controller. 不要错过将$ http注入到控制器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在POST请求触发之前,如何获取GET请求的响应主体的内容? 能做到这一点吗? - How do I get the contents of the response body of a GET request before the POST request fires? Can this be done with promise? 使用角度js ionic中的soap请求获取xml响应 - get xml response using soap request in angular js ionic 如何使用JS获取HTTP响应标头? - How can I get HTTP response header using JS? 如何在angular js中发布表单数据? 因为输入也由get请求预先填充? - How do i post a form data in angular js ? as the input is also being pre populated by a get request? 如何使用angular js在每个http请求之前销毁响应? - How to destroy the response before each http request using angular js? 等待angular js工厂请求以获取响应 - Wait for angular js factory request to get response 如何发送 POST 请求但使用自定义 useFetch 钩子反应接收响应? - How can I send a POST request but receive response using custom useFetch hook react? 如何使用getjson方法发出发布请求并获取响应? - How make post request and get response back using getjson method? 如何使用 Express/Node 从 POST 请求中获取响应数据? - how to get the response data from a POST request using Express/Node? 如何在Angular.js中自己定义的服务上获得拦截器的响应? - How can I get the response of an interceptor on my own defined service in Angular.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM