Edit 1: Guys, I notice that I call $http.get('/posts') (for some special purpose) in my authentication factory. Sorry for the stupid question. I will delete it when the bounty is end.
I have the following code to load a page https://localhost:3000/#/home
, which get all the posts from the database and display them.
The problem is that, I realise the log router.get /posts
is print twice, whereas here
and there
are only alerted once.
Does anyone know if it means that $http.get
is undertaken twice? If so, where is the problem?
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) {
... ...
In the backend:
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: I just realised one thing: I had set a login and logout on the website. When I am NOT logged in, https://localhost:3000/#/home
only shows once router.get /posts
; the problem raises when I am logged in.