angularjs - Why can't i use the $http service in a route resolve? -
i want make views show after initial data fetched , trying accomplish route resolve, can't work. doing wrong? angular skills bit shabby aplogize in advance if question dumb.
application.js :
var application = angular.module('reporterapplication', ['ngroute']); application.config(['$routeprovider', '$interpolateprovider', function($routeprovider, $interpolateprovider) { $interpolateprovider.startsymbol('<%'); $interpolateprovider.endsymbol('%>'); $routeprovider .when('/packing/scan.html', { templateurl: 'packing/scan.html', controller: 'packingscancontroller', resolve: { initdata : application.packingscaninit() } }) .when('/packing/stats.html', { templateurl: 'packing/stats.html', controller: 'packingstatisticscontroller' }) etc
and here scan.js file :
application.packingscaninit = function ($q,$timeout,$http) { var serverdata = ""; $http.get('/packing/scan.action') .success(function(data){ serverdata = data; }) .error(function(data){ serverdata = data; }); return serverdata; } application.controller('packingscancontroller', ['initdata', '$scope', '$http', function(initdata, $scope, $http) { var packer = this; // message log model packer.messagelog = [{ status : "", message : null }];
the files included in order.
service singletons means there initialized 1 time if return service called 1 time if return function service called again , again .see below sample working.
var app = angular.module('ajay.singhapp', []) .config(['$routeprovider', function($routeprovider) { $routeprovider .when('/view1', { templateurl: 'views/main.html', controller: 'mainctrl', resolve: { myvar: function (reposervice) { return reposervice.getitems().then(function (response) { return response.data; }); } } }) .when('/view2', { templateurl: 'views/main.html', controller: 'mainctrl' }) .otherwise({ redirectto: '/view1' }); }]); app.factory('reposervice', function ($http) { return { getitems: function () { return $http.get('textfile.txt'); } }; });
Comments
Post a Comment