【问题标题】:Send $http.get twice发送 $http.get 两次
【发布时间】:2017-09-13 15:57:32
【问题描述】:

编辑 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 应用和 API 是否在不同的域中?
  • 你指的是什么API?我认为 Angular 应用在​​ https://localhost:3000 中,对吧?
  • 获取帖子的 API。试图解决它是否是 CORS 问题。在 Chrome 中查看网络流量时,是否有 OPTIONS 和 GET 请求?
  • 您可以查看console.trace() 以查找第二次调用它的人。放到o.getAll方法中
  • @SoftTimur 迟早请......或者至少在原始帖子中做一个注释,这样其他人就不会浪费时间考虑这个了。

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


【解决方案1】:

既然您说当您登录时会出现问题...这是因为您使用 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 之前首先解决,然后视图被更改/更新。

一种解决方案是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2021-02-11
    • 2017-08-15
    • 2012-05-23
    相关资源
    最近更新 更多