angularjs - 发送 $http.get 两次

标签 angularjs node.js express angular-http angularjs-factory

编辑 1:伙计们,我注意到我在身份验证工厂中调用了 $http.get('/posts') (出于某些特殊目的)。对不起这个愚蠢的问题。赏金结束后我会删除它。

我有以下代码来加载页面https://localhost:3000/#/home,它从数据库中获取所有帖子并显示它们。

问题是,我意识到日志 router.get/posts 被打印两次,而 herethere 只被警告一次.

有谁知道这是否意味着 $http.get 进行了两次?如果有,问题出在哪里?

app.config(... ...) {
    $stateProvider
        .state('global', {
            templateUrl: '/htmls/global.html',
            controller: 'GlobalCtrl'
        })
        .state('global.home', {
            url: '/home',
            templateUrl: '/htmls/home.html',
            controller: 'MainCtrl',
            resolve: {
                postPromise: ['posts', function (posts) {
                    return posts.getAll();
                }]
            }
        });
}]);

app.factory('posts', ['$http', 'auth', function ($http, auth) {
    var o = { posts: [] };

    o.getAll = function () {
        alert("before");
        return $http.get('/posts').then(function (res) {
            alert("after");
            angular.copy(res.data, o.posts);
        })
    }
    ... ...
}]);

app.controller('GlobalCtrl', [function () { }]);

app.controller('MainCtrl', ['$scope', 'posts', 'auth', 'postPromise', function ($scope, posts, auth, postPromise) {
    ... ...

在后台:

router.get('/posts', function (req, res, next) {
    console.log("router.get /posts");
    Post.find(function (err, posts) {
        if (err) return next(err);
        res.json(posts);
    });
});

PS:我刚刚意识到一件事:我在网站上设置了登录和注销。当我没有登录时,https://localhost:3000/#/home 只显示一次 router.get/posts;当我登录时出现问题。

最佳答案

既然您说当您登录时会出现问题...这是因为您使用的是 angular-ui-router 这两个事件非常重要。

$stataChangeStart(...) , and $stateChangeSuccesss(...)

请告知您正在使用的解决方案

.state('global.home', {
            url: '/home',
            templateUrl: '/htmls/home.html',
            controller: 'MainCtrl',
            resolve: {
                postPromise: ['posts', function (posts) {
                    return posts.getAll();
                }]
            }
        })

在跳转到目标 url 之前首先解决,然后 View 被更改/更新。

一种解决方案是:

当您尝试先登录然后获取数据时,请确保在此处检查“&&”条件。

如果您使用的是 Angular ui 路由器版本 0.12,请升级版本以解决问题。 谢谢。

关于angularjs - 发送 $http.get 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461538/

相关文章:

node.js - 如何在 Express 中使用 Jade 的 CoffeeScript 过滤器?

angularjs - 不是预期的日期格式 - ng 和日期输入类型之间的区别

javascript - 从 https 证书中读取关键扩展

javascript - V8 会自动缓存编译的正则表达式吗?

node.js - 看到 Node.js 中的函数签名了吗?

node.js - jest 无法解析 Node 模块子路径模式导入

html - 如何使用 ng-click 从数组中删除项目或对象?

javascript - 在 ng-repeat 中使用 $http.get 会导致多个错误

html - 使用 AngularJS 在悬停时更改图像

javascript - 如何为 express.static 模拟 http.ServerResponse 和 http.IncomingMessage