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.
Since you are saying that when you are logged the problem occurs...this is because of the fact that since you are using angular-ui-router the two events are very important.
$stataChangeStart(...) , and $stateChangeSuccesss(...)
Please be informed that the resolve which you are using
.state('global.home', {
url: '/home',
templateUrl: '/htmls/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function (posts) {
return posts.getAll();
}]
}
})
is first resolved before the jump happens to the target url and then the view gets changed/updated.
One solutions is:
Please make sure that you have '&&' condition to be checked here as you are trying to login first and then get the data.
If you are using the angular ui router version 0.12 , please upgrade the version so that the issue resolves. Thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With