Я довольно новичок в AngularJS, и я хочу создать приложение, которое соответствует AngularJS style guide by John Papa. Чтобы получить хорошее представление об этой практике, я использую HotTowel skeleton.Инициализация службы общих данных в AngularJS не работает
В моем приложении я хочу использовать конечную точку HTTP API, которая извлекает информацию об аутентифицированном пользователе. Позволяет называть его example.com/api/users/me
. Эти данные должны использоваться многими контроллерами, поэтому здесь мне нужна общая служба передачи данных. Важным требованием является то, что API нельзя вызывать дважды. По этой причине я применил метод инициализации службы один раз с вызовом API. Я использовал core/dataservice.js
от HotTowel в качестве ссылки и реализованы мои службы, как это:
//File: currentUserDataService.js
(function() {
'use strict';
angular
.module('app.core')
.factory('currentUserDataService', currentUserDataService);
currentUserDataService.$inject = ['$http', '$q', 'exception', 'logger', 'config'];
/* @ngInject */
function currentUserDataService($http, $q, exception, logger, config) {
var user = {};
var service = {
init: init,
getData: getData
};
return service;
function getData(){
return user;
}
function init() {
return $http.get(config.apiBaseUrl + '/users/me')
.then(success)
.catch(fail);
function success(response) {
console.log(response.data);
user = response.data.data;
}
function fail(e) {
console.log(e);
return exception.catcher('XHR Failed for getPeople')(e);
}
}
}
})();
Теперь я хочу, чтобы потреблять эту услугу в существующих контроллеров DashboardController
и ShellController
. Мой первый шаг заключается в настройке маршрута приборной панели, чтобы решить обещание моей службы:
//File: dashboard.route.js
(function() {
'use strict';
angular
.module('app.dashboard')
.run(appRun);
appRun.$inject = ['routerHelper','currentUserDataService'];
/* @ngInject */
function appRun(routerHelper,currentUserDataService) {
routerHelper.configureStates(getStates(currentUserDataService));
}
function getStates(currentUserDataService) {
return [
{
state: 'dashboard',
config: {
url: '/',
templateUrl: 'app/dashboard/dashboard.html',
controller: 'DashboardController',
controllerAs: 'vm',
title: 'dashboard',
settings: {
nav: 1,
content: '<i class="fa fa-dashboard"></i> Dashboard'
},
resolve: {
'currentUserDataService': function(currentUserDataService){
return currentUserDataService.init;
}
}
}
}
];
}
})();
В моем понимании, я должен быть в состоянии в настоящее время для получения данных с помощью getData
функции службы от моего контроллера:
//File dashboad.controller.js
(function() {
'use strict';
angular
.module('app.dashboard')
.controller('DashboardController', DashboardController);
DashboardController.$inject = ['$q', 'currentUserDataService', 'logger'];
/* @ngInject */
function DashboardController($q, currentUserDataService, logger) {
var vm = this;
vm.user = {};
vm.title = 'Dashboard';
vm.getFullName = getFullName;
activate();
function activate() {
getCurrentUser();
logger.info('Activated Dashboard View');
}
function getCurrentUser() {
console.log(currentUserDataService);
//Interestingly I only get the init() function logged on the console
vm.user = currentUserDataService.getData(); //It fails here
console.log(vm.user);
return vm.user;
}
function getFullName(){
return vm.user.name + ' ' + vm.user.lastName;
}
}
})();
Когда я пытаюсь запустить приложение я получаю следующую ошибку
Error: currentUserDataService.getData is not a function
[email protected]://localhost:3000/src/client/app/dashboard/dashboard.controller.js:33:14
[email protected]://localhost:3000/src/client/app/dashboard/dashboard.controller.js:24:4
[email protected]://localhost:3000/src/client/app/dashboard/dashboard.controller.js:21:3
[email protected]://localhost:3000/bower_components/angular/angular.js:4640:14
[email protected]://localhost:3000/bower_components/angular/angular.js:10042:18
$ViewDirectiveFill/<.compile/<@http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:4081:28
[email protected]://localhost:3000/bower_components/angular/angular.js:9623:9
[email protected]://localhost:3000/bower_components/angular/angular.js:9022:11
[email protected]://localhost:3000/bower_components/angular/angular.js:8333:13
[email protected]://localhost:3000/bower_components/angular/angular.js:8213:30
[email protected]://localhost:3000/bower_components/angular/angular.js:8551:16
[email protected]://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:4021:23
$ViewDirective/directive.compile/</<@http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:3959:11
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17348:15
transitionTo/$state.transition<@http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:3352:11
[email protected]://localhost:3000/bower_components/angular/angular.js:15757:28
scheduleProcessQueue/<@http://localhost:3000/bower_components/angular/angular.js:15773:27
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17025:16
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:16841:15
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17133:13
[email protected]://localhost:3000/bower_components/angular/angular.js:11454:36
[email protected]://localhost:3000/bower_components/angular/angular.js:11652:7
[email protected]://localhost:3000/bower_components/angular/angular.js:11593:9
EventHandlerNonNull*createHttpBackend/<@http://localhost:3000/bower_components/angular/angular.js:11576:7
[email protected]://localhost:3000/bower_components/angular/angular.js:11423:9
$http/[email protected]://localhost:3000/bower_components/angular/angular.js:11133:16
[email protected]://localhost:3000/bower_components/angular/angular.js:15757:28
scheduleProcessQueue/<@http://localhost:3000/bower_components/angular/angular.js:15773:27
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17025:16
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:16841:15
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17133:13
[email protected]://localhost:3000/bower_components/angular/angular.js:1713:9
[email protected]://localhost:3000/bower_components/angular/angular.js:4625:16
bootstrap/[email protected]://localhost:3000/bower_components/angular/angular.js:1711:5
[email protected]://localhost:3000/bower_components/angular/angular.js:1731:12
[email protected]://localhost:3000/bower_components/angular/angular.js:1616:5
@http://localhost:3000/bower_components/angular/angular.js:30709:5
jQuery.Callbacks/[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3187:11
jQuery.Callbacks/[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3317:7
[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3536:3
[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3552:2
EventListener.handleEvent*[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3573:4
@http://localhost:3000/bower_components/jquery/dist/jquery.js:3583:1
@http://localhost:3000/bower_components/jquery/dist/jquery.js:34:3
@http://localhost:3000/bower_components/jquery/dist/jquery.js:15:2
<div ui-view="" class="shuffle-animation ng-scope">
кажется, что объект вернулся из моей службы не включает другие методы, чем init. Что не так с моим кодом?
// EDIT: Пытался ответ от @DanEEStar но теперь есть еще одна ошибка:
Error: [ ] currentUserDataService is undefined
[email protected]://localhost:3000/src/client/app/dashboard/dashboard.controller.js:33:4
[email protected]://localhost:3000/src/client/app/dashboard/dashboard.controller.js:24:4
[email protected]://localhost:3000/src/client/app/dashboard/dashboard.controller.js:21:3
[email protected]://localhost:3000/bower_components/angular/angular.js:4640:14
[email protected]://localhost:3000/bower_components/angular/angular.js:10042:18
$ViewDirectiveFill/<.compile/<@http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:4081:28
[email protected]://localhost:3000/bower_components/angular/angular.js:9623:9
[email protected]://localhost:3000/bower_components/angular/angular.js:9022:11
[email protected]://localhost:3000/bower_components/angular/angular.js:8333:13
[email protected]://localhost:3000/bower_components/angular/angular.js:8213:30
[email protected]://localhost:3000/bower_components/angular/angular.js:8551:16
[email protected]://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:4021:23
$ViewDirective/directive.compile/</<@http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:3959:11
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17348:15
transitionTo/$state.transition<@http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:3352:11
[email protected]://localhost:3000/bower_components/angular/angular.js:15757:28
scheduleProcessQueue/<@http://localhost:3000/bower_components/angular/angular.js:15773:27
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17025:16
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:16841:15
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17133:13
[email protected]://localhost:3000/bower_components/angular/angular.js:11454:36
[email protected]://localhost:3000/bower_components/angular/angular.js:11652:7
[email protected]://localhost:3000/bower_components/angular/angular.js:11593:9
EventHandlerNonNull*createHttpBackend/<@http://localhost:3000/bower_components/angular/angular.js:11576:7
[email protected]://localhost:3000/bower_components/angular/angular.js:11423:9
$http/[email protected]://localhost:3000/bower_components/angular/angular.js:11133:16
[email protected]://localhost:3000/bower_components/angular/angular.js:15757:28
scheduleProcessQueue/<@http://localhost:3000/bower_components/angular/angular.js:15773:27
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17025:16
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:16841:15
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17133:13
EventHandlerNonNull*createHttpBackend/<@http://localhost:3000/bower_components/angular/angular.js:11576:7
[email protected]://localhost:3000/bower_components/angular/angular.js:11423:9
$http/[email protected]://localhost:3000/bower_components/angular/angular.js:11133:16
[email protected]://localhost:3000/bower_components/angular/angular.js:15757:28
scheduleProcessQueue/<@http://localhost:3000/bower_components/angular/angular.js:15773:27
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17025:16
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:16841:15
$RootScopeProvider/this.$get</[email protected]://localhost:3000/bower_components/angular/angular.js:17133:13
[email protected]://localhost:3000/bower_components/angular/angular.js:1713:9
[email protected]://localhost:3000/bower_components/angular/angular.js:4625:16
bootstrap/[email protected]://localhost:3000/bower_components/angular/angular.js:1711:5
[email protected]://localhost:3000/bower_components/angular/angular.js:1731:12
[email protected]://localhost:3000/bower_components/angular/angular.js:1616:5
@http://localhost:3000/bower_components/angular/angular.js:30709:5
jQuery.Callbacks/[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3187:11
jQuery.Callbacks/[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3317:7
[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3536:3
[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3552:2
EventListener.handleEvent*[email protected]://localhost:3000/bower_components/jquery/dist/jquery.js:3573:4
@http://localhost:3000/bower_components/jquery/dist/jquery.js:3583:1
@http://localhost:3000/bower_components/jquery/dist/jquery.js:34:3
@http://localhost:3000/bower_components/jquery/dist/jquery.js:15:2
<div data-ng-animate="1" ui-view="" class="shuffle-animation ng-scope">
Спасибо за быстрый ответ! Это была действительно глупая ошибка ... Однако теперь я получаю еще одну ошибку. Я отредактировал свой ответ. – Noir
ОК, я думаю, что вторая проблема заключалась в том, что вы обновили свой сервис. В части 'resolve' имя должно быть чем-то другим. – DanEEStar
Удивительный! Это оно. Большое спасибо. :) – Noir