从index.html调用函数,该函数无限循环

calling function from index.html and the function loops indefintely

本文关键字:函数 无限循环 调用 index html      更新时间:2023-09-26

我正在尝试制作一个函数,该函数只向具有正确角色的用户显示html的特定部分。这些是我的功能:

nodejs/server.js

app.get('/api/isadmin', ensureAuthenticated, function (req, res) {
  User.findById(req.user, function (err, user) {
    res.send(user);
  });
});

这就是问题发生的地方,它将无休止地运行:

<ul ng-if="isAdmin()">
   <li>
       <a ui-sref="admin">Admin</a>
   </li>
</ul>

为什么会发生这种情况?我看过Satellizer的isAuthenticated函数,基本上也做了同样的事情。

编辑:更新代码:

adminservice.js

angular.module('App')
 .factory('AdminService', function ($q, $http, toastr) {
  return {
      getAdmin: function () {
          var httpget = $http.get('http://localhost:3000/api/isadmin');
          httpget.then(function (response) {
                var res = response.data.role;
                if (res == 'admin') {
                    console.log('true');
                    return true;
                }
                else {
                    console.log('false');
                    return false;
                }
            }, function (result) {
                return $q.reject(result);
            });
          return httpget;
      }
  };
});

navbar.js

angular.module('App')
 .controller('NavbarCtrl', function($q, $scope, $auth, AdminService) {
  $scope.isAuthenticated = function() {
     return $auth.isAuthenticated();
  };
  AdminService.getAdmin().then(
    function (result) {
        $scope.isAdmin = result;
    });
});

无论是true还是false,这两个响应仍然可以看到Admin列表元素。

我正要写很多东西。既然你已经找到并更新了你的代码,让我来解决现有的问题。您需要getAdmin函数中的promise实例return,而不是httpget

angular.module('App')
 .factory('AdminService', function ($q, $http, toastr) {
  return {
      getAdmin: function () {
          var httpget = $http.get('http://localhost:3000/api/isadmin');
          return httpget.then(function (response) {
                var res = response.data.role;
                if (res == 'admin') {
                    console.log('true');
                    return true;
                }
                else {
                    console.log('false');
                    return false;
                }
            }, function (result) {
                // just return false
                return false;
            });
      }
  };
});

你的控制器看起来不错。在html部分中,将ng-if与isAdmin属性绑定。

<ul ng-if="isAdmin">
   <li>
       <a ui-sref="admin">Admin</a>
   </li>
</ul>

希望,这有帮助。

更新

只有返回httpget才会返回promise实例,但您将在resolve函数中获得实际响应。您调用http://localhost:3000/api/isadmin时得到的响应。看到这个砰的一声:http://plnkr.co/edit/9UtYJlm9BalTi8HHTrV2?p=preview