【问题标题】:Doing HTTP request on client-side using AngularJS使用 AngularJS 在客户端执行 HTTP 请求
【发布时间】:2016-02-27 11:04:14
【问题描述】:

在成功完成this tutorial 之后,我开始构建我的应用程序路由来处理在数据库中创建一些虚拟模型,当我通过 Postman 应用程序请求它们时,它工作得很好(使用以下 URL:https://lab4 -roger13.c9users.io:8080/api/nerds)。

下一步是在 AngularJS 中创建一个服务,以允许用户在客户端请求相同的信息。在教程结束时,我得到了这个:

angular.module('NerdService', []).factory('Nerd', ['$http', function($http) {

return {
    // call to get all nerds
    get : function() {
        return $http.get('/api/nerds');
    },

    a : 2,

            // these will work when more API routes are defined on the Node side of things
    // call to POST and create a new nerd
    create : function(nerdData) {
        return $http.post('/api/nerds', nerdData);
    },

    // call to DELETE a nerd
    delete : function(id) {
        return $http.delete('/api/nerds/' + id);
    }
}       

}]);

这是链接我所有服务和路线的模块:

angular.module('sampleApp', 
['ngRoute', 'appRoutes', 'MainCtrl', 'NerdCtrl', 'NerdService'])
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
    $scope.a = Nerd.a;
}]);

这是我尝试访问的后端路由示例:

module.exports = function(app) {

    // get all nerds in the database (accessed at GET https://lab4-roger13.c9users.io:8080/api/nerds)
    app.get('/api/nerds', function(req, res) {

        // use mongoose to get all nerds in the database
        Nerd.find(function(err, nerds) {

            // if there is an error retrieving, send the error. 
                            // nothing after res.send(err) will execute
            if (err)
                res.send(err);

            res.json(nerds); // return all nerds in JSON format
        });
    });

如您所想,我可以使用 {{a}} 表示法访问 html 中服务的 a 属性,该符号显示 2。但是当我尝试使用 get 属性时,没有任何显示.

我不确定,教程在$http.get 提供的 URL 是错误的还是我错过了访问 GET 响应的步骤?

(如果我遗漏了任何相关代码,它们与可以在tutorial link 找到的代码相同)

【问题讨论】:

  • get 返回一个函数,而不是静态属性。

标签: angularjs node.js http crud


【解决方案1】:

Nerd.get() 是一个从$http 服务返回承诺的函数。如果你想在你的视图中显示它的结果,你可以像这样将结果绑定到你的视图:

.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
    Nerd.get().then(function(nerds) {
        $scope.nerds = nerds;
    });
}]);

【讨论】:

  • 使用 $scope 或将变量附加到控制器有什么区别?在文档中,大多数时候我看到它附加到控制器上,当我尝试使用 $scope 时它不会工作。此外,当我尝试将变量附加到控制器而不是使用 $scope 时,它​​也不起作用......
  • 这取决于您是否使用controllerAs 语法。我以为你不是,因为你的代码使用了$scopeHere's a good article explaining the differences.
  • 非常感谢,我现在用这个而不是 $scope 让它正常工作了!我已经实现了创建和删除功能,它们工作得很好。我注意到的一个问题是,虽然最后两个似乎会立即更新数据库(与 Postman 一起检查),但 get 方法似乎一直在获取它的旧版本,您对它可能是什么有任何提示?
【解决方案2】:

喜欢这篇文章我在使用工厂时遇到了一些问题,并在这里找到了解决方案 书呆子控制器

angular.module('NerdCtrl', []).controller('NerdController', function($scope, Nerd) {


    $scope.tagline = 'bla bla';

    $scope.nerds = {};
    Nerd.getNerd()
        .then(function (components) {
            $scope.nerds = components;
        }, function (error) {
            console.error(error);
        });

});

作为服务

angular.module('NerdService', []).factory('Nerd', function ($q, $http) {
    return {
      getNerd: function () {
        var deferred = $q.defer(),
          httpPromise = $http.get('/api/nerds');

        httpPromise.success(function (components) {
          deferred.resolve(components);
        })
          .error(function (error) {
            console.error('Error: ' + error);
          });

        return deferred.promise;
      }
   };
});

在 NerdHTLM 中使用控制器循环记录

<table ng-controller="NerdController" >
    <tbody>
        <tr ng-repeat="nerd in nerds">
            <td>{{nerd.name}}</td>
            <td>{{nerd.type}}</td>
        </tr>
    </tbody>
</table>

【讨论】:

  • 我在这里link 找到了关于工厂从 MongoDB 检索数据的很好的解释。请享用 ! (谢谢罗杰和阿尼德)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多