【发布时间】:2017-09-13 15:57:32
【问题描述】:
编辑 1:伙计们,我注意到我在身份验证工厂中调用了 $http.get('/posts') (出于某些特殊目的)。对不起这个愚蠢的问题。赏金结束后我会删除它。
我有以下代码来加载页面https://localhost:3000/#/home,它从数据库中获取所有帖子并显示它们。
问题是,我意识到日志router.get /posts 被打印两次,而here 和there 只被警告一次。
有谁知道这是否意味着$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