我正在学习如何通过本教程https://thinkster.io/angulartutorial/angular-rails/
将Angularjs与ROR一起使用我正处于这样一个阶段,当我为一个服务添加一个新函数时,它应该得到我在db中的所有帖子。但是,当我运行代码时,页面不再加载,我的服务器日志中没有数据库调用。在进行此更改之前,一切正常。如果有人可以看一下,那就太好了。请注意,我的Rails路由返回json就好了。
app.js
angular.module('flapperNews', ['ui.router', 'templates'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: 'posts/_posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
文章/ posts.js
angular.module('flapperNews')
.factory('posts', [
'http',
function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data){
angular.copy(data, o.posts);
});
};
return o;
}]);
文章/ postsCtrl.js
angular.module('flapperNews')
.controller('PostsCtrl', [
'$scope',
'$stateParams',
'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}]);
家/ mainCtrl.js
angular.module('flapperNews')
.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.posts = posts.posts;
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0,
comments: [
{author: 'Joe', body: 'Cool post!', upvotes: 0},
{author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0}
]
});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
}
}]);
答案 0 :(得分:1)
您注入工厂的命名http服务是'http',它应该是'$ http',然后您可以在工厂函数中为其命名
angular.module('flapperNews')
.factory('posts', [
'http',
function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data){
angular.copy(data, o.posts);
});
};
return o;
}]);
应该是
angular.module('flapperNews')
.factory('posts', [
'$http',
function(anyName){
var o = {
posts: []
};
o.getAll = function() {
return anyName.get('/posts.json').success(function(data){
angular.copy(data, o.posts);
});
};
return o;
}]);
答案 1 :(得分:0)
由于AngularJS有1.5+版本,因此这是处理$ http:
响应的更好方法angular.module('flapperNews')
.factory ('posts', ['$http', function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json')
.then(function onSuccess(response) {
angular.copy(response.data, o.posts);
}, function onError(response) {
window.alert('Error: ' + response.status + " - " +response.statusText);
});
};
return o;
}])
并记得将你的posts.json保存在/ public文件夹中!