Sof*_*mur 9 node.js express angularjs angularjs-factory angular-http
编辑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) {
... ...
Run Code Online (Sandbox Code Playgroud)
在后端:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
PS:我刚刚意识到一件事:我在网站上设置了登录和注销.当我没有登录时,https://localhost:3000/#/home只显示一次router.get /posts; 我登录时问题就出现了.
既然你说当你登录时就会出现问题......这是因为由于你使用的是 Angular-ui-router,这两个事件非常重要。
$stataChangeStart(...) , and $stateChangeSuccesss(...)
Run Code Online (Sandbox Code Playgroud)
请注意,您正在使用的解析
.state('global.home', {
url: '/home',
templateUrl: '/htmls/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function (posts) {
return posts.getAll();
}]
}
})
Run Code Online (Sandbox Code Playgroud)
在跳转到目标 url 之前首先解决,然后视图被更改/更新。
一种解决方案是:
请确保您在此处检查“&&”条件,因为您尝试先登录然后获取数据。
如果您使用的是 Angular ui 路由器版本 0.12 ,请升级版本以便解决问题。谢谢。
| 归档时间: |
|
| 查看次数: |
698 次 |
| 最近记录: |