Q&A
angular 1.6.4
angular-route 1.6.4
を使っています。
下記のapplication.jsでは、
/adminにアクセスすると/userからデータを取得して、undefinedでなければviews/admin.client.view.htmlのテンプレートを表示するようにしようとしています。
しかし、/adminにアクセスしても、getUserProviderのgetInfo()が呼ばれていないようです。
Providerの書き方、使い方が間違っていると思いますが、どのように直したらよいでしょうか。
よろしくお願いします。
lang
1'use scrict'; 2 3angular.module('myApp', ['ngRoute', 'users', 'admin']); 4 5angular.module('users', []); 6 7angular.module('users').factory('Authentication', [ '$http', 8 function($http) { 9 var user; 10 $http.get('/user').then(function(data) { 11 console.log(data); 12 if (data.user) { 13 user = data.user; 14 } else { 15 user = undefined; 16 } 17 }); 18 return { 19 user: user 20 }; 21 } 22]); 23 24angular.module('admin', ['users']); 25 26angular.module('admin'). 27controller('AdminController', ['$scope', 'Authentication', 28 function($scope, Authentication) { 29 $scope.authentication = Authentication; 30 } 31]). 32provider('getUser', function GetUser() { 33 this.$get = ['$http', function($http) { 34 return { 35 getInfo : function() { 36 console.log('getInfo called.'); 37 $http.get('/user').then(function(data) { 38 console.log('getInfo', data); 39 return data.user; 40 },function(error) { 41 console.log(error); 42 }); 43 } 44 }; 45 }]; 46}). 47config(['$routeProvider', '$locationProvider', 'getUserProvider', 48 function($routeProvider, $locationProvider, getUserProvider) { 49 $locationProvider.html5Mode(true); 50 $routeProvider. 51 when('/', { 52 templateUrl: 'views/root.client.view.html' 53 }). 54 when('/admin', { 55 templateUrl: 'views/admin.client.view.html', 56 resolve: { 57 "check": function($location) { 58 if (getUserProvider.getInfo() === undefined) { 59 $location.path('/'); 60 } 61 } 62 } 63 }); 64 } 65]);
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2017/05/10 02:50
2017/05/10 04:29