带有Angular的Http请求服务抛出错误 [英] Http request service with Angular throwing an error

查看:26
本文介绍了带有Angular的Http请求服务抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个服务,该服务向我的路由 (NodeJs) 发出 http 请求,以将用户添加到数据库中.

如果我只是将它写在控制器中它可以工作,但是在我刷新浏览器之前你不会看到添加的用户:

我在控制器中的代码:

//添加用户到db的函数$scope.inviteUser = function(){$http.post('/api/users/invite', {'email': $scope.user.email,'role_id':$scope.user.role}, {标题:{内容类型":文本/纯文本"}}).success(function(data, status, headers, config) {console.log("成功将用户保存到数据库", data);$scope.userInfo.push(data);}).error(function(data, status, headers, config) {console.log("添加用户到数据库失败");});}

我在服务中需要它的原因是因为堆栈上的人告诉我它可以解决我目前面临的问题,即当添加用户时,在刷新浏览器之前您不会看到它.这是因为我有一个带有按钮邀请的视图,当您单击它时会显示一个弹出窗口(md-dialog -> angular material).这个对话框有它自己的 tmple.html 文件.在邀请按钮所在的视图中是 $scope.userInfo 链接到(在函数邀请用户 - 上面的代码中定义)

带有邀请按钮的视图和添加用户的列表的代码:

对话框代码:

 <表单名称=表单"><md-工具栏><div class="md-toolbar-tools"><h1 class="customH1">邀请用户</h1><span flex></span><!-- <md-button class="md-icon-button" ng-click="closeDialog()"><md-icon md-svg-src="images/ic_close_24px.svg" aria-label="关闭对话框"></md-icon></md-button>-->

</md-工具栏><md-dialog-content><div id="containerForm"><div layout="row"><md-input-container flex=""><div class="form-group" ng-class="{ 'has-success': form.email.$valid && submit,'has-error': form.email.$invalid &&已提交 }"><label>输入用户的电子邮件</label><input type="email" name="email" id="to" class="form-control" ng-model="user.email" required mongoose-error/><p class="help-block" ng-show="form.email.$error.email && submit">看起来不是有效的电子邮件.</p><p class="help-block" ng-show="form.email.$error.required && submit">你的电子邮件地址是什么?</p><p class="help-block" ng-show="form.email.$error.mongoose">{{errors.email }}</p>

</md-input-container>

<br/><br/><div ng-show="form.email.$dirty && form.email.$valid"><h5>分配以下角色之一:</h5><div id="wrapperRadioButtons"><md-radio-group ng-model="user.role"><md-radio-button ng-repeat="userrole in roleInfo" value="{{userrole.id}}" class="md-primary">{{userrole.role}}</md-radio-按钮></md-radio-group>

<br/>

</md-dialog-content><div class="md-actions" layout="row" ><md-button ng-click="closeDialog()" class="md-primary">取消</md-button><md-button id="send_email" ng-click="inviteUser(); closeDialog()" class="md-primary">邀请</md-button>

</表单></md-dialog>

这是我编写并尝试链接到函数inviteUsers的服务:

zazzleApp.factory('UserService', ['$q', '$http', function ($q, $http) {无功服务 = {};service.get = function() {var deferred = $q.defer();deferred.resolve(service.data);返回 deferred.promise;}service.save = 函数(数据){var 承诺 = $http({方法:'POST',网址:'api/users/invite'})var deferred = $q.defer();service.data.push(data);deferred.resolve();返回 deferred.promise;}退货服务;}]);

我的控制器的一部分:

angular.module('zazzleToolPlannerApp').controller('CalendarCtrl', function ($scope, $mdDialog, $http, $rootScope, $timeout, User, Auth, UserService) {//添加用户到数据库的函数$scope.inviteUser = function(){变量对象 = {'email': $scope.user.email,'role_id':$scope.user.role};UserService.save(obj).then(function(){$scope.getUsers();})}});

现在当我尝试添加用户时,我的控制台出现错误 -> https://gyazo.com/34b39d7eda18b89afd9a410

所以基本上我要问的是如何编写一个发出 http 请求并将其链接到控制器的服务......

旁注:我以前从未这样做过,所以这就是它可能不起作用的原因.

解决方案

你在控制台出错的原因是因为 service.data.push(data) 中的 service.data; 不存在.您的意思可能是将新用户推送到尚未创建的用户数组中(您似乎对代码中的数据"感到困惑:P).

无论如何,您的问题的解决方案要简单得多:在服务中,您可以将 $http.post() 返回给控制器,并通过 .success() 回调处理控制器中的请求.此外,您需要更新的用户列表应位于服务中,并且您从控制器绑定到它;这样,它会在您添加新用户后保持模板更新,而无需刷新浏览器.您只需要从服务中检索 $http 回调上的用户列表.

如果你仍然觉得这令人困惑,我可以写一个小提琴.

编辑:这是小提琴:http://jsfiddle.net/bosch/8pnL23k7/.希望它能帮助你更好地理解这些概念

I am trying to write a service that makes a http request to my route (NodeJs) to add a user to the db.

If I just write it in the controller it works but then you won't see the user added until I refresh the browser:

my code in the controller:

//Function to add a user to the db
$scope.inviteUser = function(){
    $http.post('/api/users/invite', {
        'email': $scope.user.email,
        'role_id': $scope.user.role
    }, {
        headers: {
            "Content-Type": "text/plain"
        }
    })
    .success(function(data, status, headers, config) {
        console.log("Successfully saved a user to the DB", data);

        $scope.userInfo.push(data);


    })
    .error(function(data, status, headers, config) {
        console.log("Failed to add user to DB");
    });
}

The reason I need it in a service is because people on stack told me that it would resolve the issue that I am currently facing that is when a user is added you won't see it until the browser is refreshed. This is because I have a view with a button invite and when you click on it a popup shows (md-dialog -> angular material). This dialog has its own tmple.html file. In the view where the invite button resides is the $scope.userInfo linked to (defined in the function inviteUser - code from above)

Code for the view with the invite button and the list where the user get added:

<div id="sidebar" class="md-whiteframe-z4" ng-data-color="">
      <div style="height: 80px;"></div>
      <div class="userList">
        <li id="customLI" ng-repeat="user in userInfo" id="userPos" class="circular md-whiteframe-z2" style="background-color: {{ user.color }} " ng-click=" showPopUpDeletionConfirmation(); setDeleteId( user._id )" ng-data-id="{{ user._id }} ">
          <p class="initials" id="userValue" style="top: {{ user.top }};" >
              <custom id="user._id"></custom>
              {{user.initials}}
          </p>
        <md-tooltip>
        <!-- Delete this user -->  {{user.name}}
        </md-tooltip>
        </li>
      </div>
    </div>

Code of the dialog box :

  <md-dialog aria-label="" ng-controller="CalendarCtrl">
    <form name="form"  >
      <md-toolbar>
        <div class="md-toolbar-tools">
          <h1 class="customH1">Invite a user</h1>

          <span flex></span>
          <!-- <md-button class="md-icon-button" ng-click="closeDialog()">
            <md-icon md-svg-src="images/ic_close_24px.svg" aria-label="Close dialog"></md-icon>
          </md-button> -->
        </div>
      </md-toolbar>
      <md-dialog-content>
        <div id="containerForm">
            <div layout="row">
              <md-input-container flex="">
                <div class="form-group" ng-class="{ 'has-success': form.email.$valid && submitted,'has-error': form.email.$invalid && submitted }">
                  <label>Enter the user's e-mail</label>
                  <input type="email" name="email" id="to" class="form-control" ng-model="user.email" required mongoose-error/>
                  <p class="help-block" ng-show="form.email.$error.email && submitted">
                    Doesn't look like a valid email.
                  </p>
                  <p class="help-block" ng-show="form.email.$error.required && submitted">
                    What's your email address?
                  </p>
                  <p class="help-block" ng-show="form.email.$error.mongoose">
                    {{ errors.email }}
                  </p>
                </div>
              </md-input-container>
            </div>  

            <br /><br />

            <div ng-show="form.email.$dirty && form.email.$valid">
              <h5>Assign one of the following role's:</h5>

              <div id="wrapperRadioButtons">
                <md-radio-group ng-model="user.role">
                  <md-radio-button ng-repeat="userrole in roleInfo" value="{{userrole.id}}" class="md-primary">{{userrole.role}}</md-radio-button>
                </md-radio-group>
              </div>
              </div>

            <br />

        </div>
      </md-dialog-content>
      <div class="md-actions" layout="row" >
        <md-button ng-click="closeDialog()" class="md-primary">Cancel</md-button>

        <md-button id="send_email" ng-click="inviteUser(); closeDialog()" class="md-primary">Invite</md-button>
      </div>
    </form>
  </md-dialog>

This is the service I wrote and tried to link to the function inviteUsers:

zazzleApp.factory('UserService', ['$q', '$http', function ($q, $http) {
            var service = {};

            service.get = function() {
              var deferred = $q.defer();

              deferred.resolve(service.data);
              return deferred.promise;
            }

            service.save = function(data) {
                var promise = $http({
                    method: 'POST',
                    url: 'api/users/invite'
                })

                var deferred = $q.defer();

                service.data.push(data);
                deferred.resolve();
                return deferred.promise;
            }

            return service;
        }
    ]);

Part of my controller:

angular.module('zazzleToolPlannerApp')
    .controller('CalendarCtrl', function ($scope, $mdDialog, $http, $rootScope, $timeout, User, Auth, UserService) {

        //Function to add a user to the db
        $scope.inviteUser = function(){

           var obj = {
                'email': $scope.user.email,
                'role_id': $scope.user.role
           };
           UserService.save(obj).then(function(){
                $scope.getUsers();

           })
        }
});

Now when I try to add a user I get an error in my console -> https://gyazo.com/34b39d7eda18b8afd9ef11094b4f429a

So basically what I am asking is how to write a service that makes an http request and link it to a controller ....

Side note: I have never done this before so thats why its probably not working.

解决方案

The reason you get an error in the console is because service.data in service.data.push(data); does not exist. What you meant was probably to push the new user into an array of users which has not been created yet (and you seem confused about the "data" in the code:P).

Anyway, the solution for your problem is much simpler: in the service you can return the $http.post() to the controller and process the request in the controller on the .success() callback. Further, the list of users that you need updated should reside in the service and you bind to it from your controller; this way it will keep the template updated after you add a new user without refreshing the browser. You just have to retrieve the list of users on the $http callback from the service.

I can write a fiddle if you still find this confusing.

EDIT: here is the fiddle: http://jsfiddle.net/bosch/8pnL23k7/. Hope it will help you understand the concepts better

这篇关于带有Angular的Http请求服务抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆