我试图在我经历的angular-rails tutorial上实施用户的个人资料页面。我按以下顺序:
/javascripts/users/_users.html
User's Profile Page
{{user.email}}
/javascripts/users/users.js
angular.module('flapperNews').factory('users', ['$http', function($http){
var o = {
users: []
};
o.get = function(id) {
return $http.get('/users/' + id + '.json').then(function(res){
return res.data;
});
};
return o;
}])
/javascripts/users/usersCtrl.js
angular.module('flapperNews')
.controller('UsersCtrl', [
'$scope',
'users',
'user',
function($scope, users, user){
$scope.user = user;
}])
我的app.js
州反映了这种变化:
.state('users', {
url: '/users/{id}',
templateUrl: 'users/_users.html',
controller: 'UsersCtrl',
resolve: {
post: ['$stateParams', 'users', function($stateParams, users) {
return users.get($stateParams.id);
}]
}
})
用户的控制器如下所示:
class UsersController < ApplicationController
respond_to :json
def show
respond_with User.find(params[:id])
end
end
路线:
Rails.application.routes.draw do
devise_for :users
devise_for :installs
root to: 'application#angular'
resources :posts, only: [:create, :index, :show] do
resources :comments, only: [:show, :create] do
member do
put '/upvote' => 'comments#upvote'
end
end
member do
put '/upvote' => 'posts#upvote'
end
end
resources :users
end
使用user id = 2
登录并尝试点击个人资料页面时,似乎会通过:
Started GET "/users/2.json" for ::1 at 2015-10-27 23:07:23 -0400
Processing by UsersController#show as JSON
Parameters: {"id"=>"2"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Completed 200 OK in 5ms (Views: 0.6ms | ActiveRecord: 0.1ms)
但在实际的页面上,我留下了硬编码:
User's Profile Page
{{user.email}}
我觉得我错过了一些简单的想法,任何想法都可能出错?
答案 0 :(得分:1)
您的return语句在$http
调用实际填充数据之前执行。您需要使用$q
。
在服务中:
var deferred = $q.defer();
$http.get('job.json')
.success(function(response) {
defer.resolve(response);
}).error(function(error) {
console.log(error);
})
return deferred.promise;
在控制器中:
var p = <serviceCall>
p.then(function(s){
$scope.ans=s;
})
$q
用于获取同步响应。有关详细信息,请阅读 Angular Docs :https://docs.angularjs.org/api/ng/service/ $ q