与角度抛出错误Http请求服务

与角度抛出错误Http请求服务

问题描述:

我试图写一个服务,使一个HTTP请求到我的路线(的NodeJS)将用户添加到数据库。

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:

我的code控制器:

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

我需要在服务的原因是因为人们对堆栈告诉我,这将解决我目前面临的是当用户添加你不会看到它,直到刷新浏览器的问题。这是因为我有一个按钮,以便邀请,当你点击它弹出显示(MD-对话框 - >角材料)。这个对话框有自己的tmple.html文件。在邀请按钮所在的视图是在$ scope.userInfo挂(在函数中定义inviteUser - 从上面code)

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与邀请按钮,当用户被添加列表视图:

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:

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>

这是我写的,并试图链接到功能inviteUsers服务:

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

           })
        }
});

现在,当我尝试添加一个用户我得到了我的控制台错误 - > https://gyazo.com/34b39d7eda18b8afd9ef11094b4f429a

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

所以基本上我问的是如何写一个服务,使HTTP请求并将其链接到一个控制器....

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.

在控制台得到一个错误的原因是因为在 service.data.push的 service.data ​​ em>的(数据); 不存在。你的意思可能是给新用户推到已尚未创建的用户数组(好像你困惑于code数据:P)。

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

总之,您问题的解决方案要简单得多:
在服务,您可以返回$ http.post()的控制器和过程中的.success()回调控制器的请求。此外,你需要更新的用户列表应位于该服务,你从你的控制器绑定到它;这样一来就会让你添加新用户,而无需刷新浏览器之后更新的模板。你只需要检索从服务$ HTTP回调的用户列表。

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.

修改:这里是提琴: http://jsfiddle.net/bosch / 8pnL23k7 / 。希望这将有助于你理解的概念更好地

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