问题描述
我想在angular.module使用服务。
I want use a service in a angular.module.
我有一个 record.js
为 RecordCtrl
,我想用 requestCurrentUser
中存在的 sessionService.js
。我使用会话
控制器和服务之间传递数据。我送从记录,JS
按 requestCurrentUser
功能的请求象下面这样:
I have a record.js
for RecordCtrl
and I want use requestCurrentUser
fnction that exist in sessionService.js
. I use Session
for pass data between controller and service. I send a request from record,js
by requestCurrentUser
function like below:
'use strict';
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records',function($scope, Session, Records){
$scope.user = Session.requestCurrentUser();
}]);
和我收到这在 sessionService.js
象下面这样:
and I recieve this in sessionService.js
like below:
'use strict';
angular.module('sessionService', [])
.factory('Session', function($location, $http, $q) {
var service = {
requestCurrentUser: function() {
return $http.get('/api/users').then(function(response) {
service.currentUser = response.data.user;
return service.currentUser;
);
}
},
currentUser: null,
return service;
});
我可以在 requestCurrentUser
正确地获取数据,但我不能接受她在 record.js
此数据。当我回响在 sessionService.js
的数据,我可以看到下面的数据:
I can get data correctly in requestCurrentUser
, but I cannot recieve this data in record.js
. When I echo data in sessionService.js
, I can see below data:
Object {id: 2, email: "mgh@mgh.com", created_at: "2014-08-11T08:37:59.981Z", updated_at: "2014-08-26T08:03:27.702Z"}
但我不能接受她在 record.js
这个数据,我得到一个空的对象,象下面这样:
But I cannot recieve this data in record.js
and I get an empty object like below:
[object Object]
我觉得code的问题是关于会话
我在2 JS
文件(使用 record.js
和 sessionService.js
)。对于添加的依赖,我有一个 app.js
包含在这个依赖。
I think the problem of code is about Session
that I use in 2 js
file(record.js
and sessionService.js
). For add dependency, I have a app.js
that include dependencies on this.
app.js
:
'use strict';
angular.module('app',['ngRoute', 'ngResource', 'sessionService', 'recordService'])
我找不到这个问题,我想补充 sessionService.js
到 record.js
按低于code
app.service('sessionService');
但问题没有解决。我不知道我怎么能解决这个问题呢?任何一个有想法解决这个问题?
But the problem isn't fix. I don't know how can I resolve this problem? Any one have idea for fix this problem?
推荐答案
它可以固定如下:
'use strict';
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records',function($scope, Session, Records){
Session.requestCurrentUser().then(function(data) {
$scope.user = data;
});
}]);
这篇关于Angularjs:添加服务angular.module的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!